方法Swizzling不适用于UIViewController的类别

时间:2015-07-01 09:37:20

标签: ios objective-c uiviewcontroller viewwillappear method-swizzling

我使用普通的混合方法:

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);
    }
}

我想与viewWillAppear:交换xxx_viewWillAppear:。所以我创建了一个UIViewController类,并创建方法xxx_viewWillAppear:

如果我使用dispatch_once方法中的+(void)load来调用swizzleMethod,那么一切都会出错。

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        swizzleMethod([self class], @selector(viewWillAppear:), @selector(xxx_viewWillAppear:));
    });
}

它将调用UIViewController中的viewWillAppear:,并在调用[super viewWillAppear:animated]时调用xxx_viewWillAppear

但是如果我把load方法放在UIViewController中(不在类别中),它就是正确的。

那么,为什么?

我使用xcode 6和iOS 8。

0 个答案:

没有答案