函数替换 oc的运行时

来源:互联网 发布:团队协作工具 知乎 编辑:程序博客网 时间:2024/06/11 09:12
BOOL swizzle(Class c,SEL origSelector, SEL newSelector){    Method origMethod = class_getInstanceMethod(c, origSelector);    Method newMethod = class_getInstanceMethod(c, newSelector);        if (origMethod && newMethod) {        if (class_addMethod(c, origSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))) {            class_replaceMethod(c, newSelector, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));        } else {            method_exchangeImplementations(origMethod, newMethod);        }        return YES;    }    return NO;}

以下是替换后的使用:

        SEL ors = @selector(haha);
        SEL news = @selector(oooo);
        Class c = NSClassFromString(@"Test1");
        
        BOOL succesed = swizzle(c,ors,news);

        [self haha];