I use the normal swizzle method:
void swizzleMethod(Class class, SEL originalSelector, SEL swizzledSelector)
{
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
}
else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
}
I want to exchange viewWillAppear:
with xxx_viewWillAppear:
. So I create a category of UIViewController and create the method xxx_viewWillAppear:
.
If I use dispatch_once
in the +(void)load
method to call swizzleMethod
, everything goes wrong.
+ (void)load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
swizzleMethod([self class], @selector(viewWillAppear:), @selector(xxx_viewWillAppear:));
});
}
It would call the viewWillAppear:
in the UIViewController, and when [super viewWillAppear:animated]
was called, xxx_viewWillAppear
was called.
But if I put the load method in the UIViewController (not in the category), it goes right.
So, Why?
I use xcode 6 and iOS 8.