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];