美文网首页
iOS开发- runtime方法交换

iOS开发- runtime方法交换

作者: Simple_Code | 来源:发表于2020-08-06 14:35 被阅读0次
+ (void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Method originalMethod = class_getInstanceMethod([self class], @selector(originalMethod));
        Method swizzlingMethod = class_getInstanceMethod([self class], @selector(swizzlingMethod));
        BOOL isAdded = class_addMethod([self class], method_getName(originalMethod), method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
//添加不存在的方法,返回Yes;
        if (isAdded)
        {
            NSLog(@"方法在原类中不存在,已经添加成功,用下面的方法替换其实现");
            class_replaceMethod([self class], method_getName(originalMethod), method_getImplementation(swizzlingMethod), method_getTypeEncoding(swizzlingMethod));
        }
        else
        {
            NSLog(@"方法在原类中存在,用下面的方法交换其实现方法");
            method_exchangeImplementations(originalMethod, swizzlingMethod);
        }
        
        NSLog(@"end");
    });
    
}
- (void)originalMethod{
    NSLog(@"原类中的方法");
}


- (void)swizzlingMethod{
    NSLog(@"替换过的方法");
}

相关文章

网友评论

      本文标题:iOS开发- runtime方法交换

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