美文网首页
iOS开发·runtime动态方法交换

iOS开发·runtime动态方法交换

作者: 富城 | 来源:发表于2021-01-27 15:57 被阅读0次

    为了方便使用,将动态方法交换的主体代码提取下

    + (void)load {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            Class class = [self class];
            
            SEL originalSelector = @selector(<#method#>);
            SEL swizzledSelector = @selector(<#new_method#>);
            
            Method originalMethod = class_getInstanceMethod(class, originalSelector);
            Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
            
            BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
            
            if (didAddMethod) {
                class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
            } else {
                method_exchangeImplementations(originalMethod, swizzledMethod);
            }
            
        });
    }
    

    相关文章

      网友评论

          本文标题:iOS开发·runtime动态方法交换

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