美文网首页
iOS 方法交换

iOS 方法交换

作者: XPorter | 来源:发表于2017-03-22 16:16 被阅读0次

交换类方法

void SwizzleClassMethod(Class c, SEL orig, SEL new) {    
    Method origMethod = class_getClassMethod(c, orig);
    Method newMethod = class_getClassMethod(c, new);
    c = object_getClass((id)c);
    if(class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {
        class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
    } else {
        method_exchangeImplementations(origMethod, newMethod);
    }
}

交换实例方法

void SwizzleInstanceMethod(Class c, SEL orig, SEL new) {
    Method origMethod = class_getInstanceMethod(c, orig);\
    Method newMethod = class_getInstanceMethod(c, new);\
    BOOL didAddMethod = class_addMethod(c, orig,method_getImplementation(newMethod),method_getTypeEncoding(newMethod));
    if (didAddMethod) {
        class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
    } else {
        method_exchangeImplementations(origMethod, newMethod);
    }
}

相关文章

网友评论

      本文标题:iOS 方法交换

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