Objective C 中的方法调配

Method swizzling in Objective C

我正在学习 Objective C 中的 swizzling 方法。下面是我的 swizzle

代码
+(void)load{
NSLog(@"Load %@",[self class]);

static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{

    Class class = [self class];

    SEL originalSelector = @selector(viewWillAppear:);
    SEL swizzlingSelector = @selector(logging_viewWillAppear:);

    Method origialMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzlingMethod = class_getInstanceMethod(class, swizzlingSelector);



    BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzlingMethod), method_getTypeEncoding(swizzlingMethod));

    if (didAddMethod) {
        class_replaceMethod(class, swizzlingSelector, method_getImplementation(origialMethod), method_getTypeEncoding(origialMethod));
    }
    else{
        method_exchangeImplementations(origialMethod, swizzlingMethod);
    }
});
}

-(void)logging_viewWillAppear:(BOOL)animated{
[self logging_viewWillAppear:animated];
NSLog(@"Logging viewWillAppear");
}

一切正常。但是 BOOL didAddMethod 总是 returns NO。我想了解我们将得到 didAddMethod = YES 的场景是什么。

您使用的方法是否正确?

Adds a new method to a class with a given name and implementation. class_addMethod will add an override of a superclass's implementation, but will not replace an existing implementation in this class. To change an existing implementation, use method_setImplementation.

这个方法returns:

YES if the method was added successfully, otherwise NO (for example, the class already contains a method implementation with that name).