0

我使用正常的调酒方法:

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

它会viewWillAppear:在 UIViewController 中调用,当[super viewWillAppear:animated]被调用时,xxx_viewWillAppear被调用。

但是如果我将加载方法放在 UIViewController 中(不在类别中),它就会正确。

所以为什么?

我使用 xcode 6 和 iOS 8。

4

0 回答 0