Method-Swizzling&动态添加方法&动态方法解析

2018-12-24  本文已影响0人  滨滨_57b5

Method-Swizzling

+ (void)load {
    //获取方法的选择器获取到Method类型的方法
    Method test = class_getInstanceMethod(self, @selector(test));
    
    Method other = class_getInstanceMethod(self, @selector(otherTest));
    
    //交换方法
    method_exchangeImplementations(test, other);
}

- (void)test {
    NSLog(@"test");
}

- (void)otherTest {
    [self otherTest];
     NSLog(@"otherTest");
}

动态添加方法

oid testIMP(void) {
    NSLog(@"test invoke");
}


+ (BOOL)resolveInstanceMethod:(SEL)sel {
    if (sel == @selector(test)) {
        
        class_addMethod(self, @selector(test), testIMP, "V@:");
        
        return YES;
    }else {
        return [super resolveInstanceMethod:sel];
    }
}

动态方法解析 @dynamic

上一篇 下一篇

猜你喜欢

热点阅读