Method swizzling for all instances of class

May 3rd, 2012
#reflection

I've been dealing recently a lot with OCMock and while is great there is some draw backs for it. The major one that I had was when I was writing integration tests for a legacy library that we have. I needed to override a method of an object that was inside a method that I was testing (so it would always return the same value). However as I didn't have that object in hand I couldn't mock it, changing the method to inject the object was a no-go because of the number of other projects that this change would have impacted so my only option was to mess around with the Objective-C runtime and inject my instance method into it so that it would override that instance method for all object of a certain type:

#import <objc/runtime.h>

....

- (void)swizzleInstanceMethodForInstancesOfClass:(Class)targetClass selector:(SEL)selector
{
    originalMethod = class_getInstanceMethod(targetClass, selector);
    swizzleMethod = class_getInstanceMethod([self class], selector);
    method_exchangeImplementations(originalMethod, swizzleMethod);
}

- (void)deswizzle
{
    method_exchangeImplementations(swizzleMethod, originalMethod);
    swizzleMethod = nil;
    originalMethod = nil;
}

What do you think? Let me know by getting in touch on Twitter - @wibosco