OCMock method flushing for all class instances

I want to mock the instance method for all instances of the class using OCMock, however I don’t have an instance of the class to override it, but it is created inside the method I'm testing.

So my question is: is it possible to override this method for all instances of the class, or will I need to insert this instance into the method, and not create it inside the method?

i.e.

[[ClassThatHasTheInstanceMethodToOverride andCall:@selector(callThisMethodInstead) onObject:self] someInstanceMethod];
+5
source share
1 answer

In the end, I got this set of methods:

Method originalMethod = nil; Method swizzleMethod = nil;

#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;
}
+1
source

All Articles