objective-cswizzling

Method swizzling in Objective C


I am learning method swizzling in Objective-C. Below is my code to 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");
}

Everything is working fine. But the BOOL didAddMethod always returns NO. I would like to understand what is the scenario we will get didAddMethod = YES.


Solution

  • Are you using the correct method?

    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.

    This method returns:

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