美文网首页
Method-Swizzling&动态添加方法&动态方法解析

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

作者: 滨滨_57b5 | 来源:发表于2018-12-24 14:52 被阅读0次

    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

    • 动态运行时语言,当把属性声明为 @dynamic时,表示不需要编译器在编译时为我们生成set和get方法,而是在运行时具体调用了set或get方法时,再去添加具体的实现
    • 编译时语言在编译期进行函数决议

    相关文章

      网友评论

          本文标题:Method-Swizzling&动态添加方法&动态方法解析

          本文链接:https://www.haomeiwen.com/subject/shhzkqtx.html