objective-c iPhone 设备上的方法 Swizzle
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1637604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Method Swizzle on iPhone device
提问by dizy
I tried both JRSwizzle, and MethodSwizzle. They compile fine on the simulator but throw a bunch of errors when I try to compile for Device (3.x)
我尝试了 JRSwizzle 和 MethodSwizzle。它们在模拟器上编译得很好,但是当我尝试为 Device (3.x) 编译时抛出了一堆错误
Has anyone had any luck swizzling on the iphone? Whats the trick?
有没有人在 iphone 上有过运气?有什么诀窍?
TIA
TIA
回答by Brad Larson
The CocoaDev wiki has an extensive discussion on method swizzling here. Mike Ash has a relatively simple implementation at the bottom of that page:
CocoaDev wiki 在此处对方法 swizzling 进行了广泛的讨论。Mike Ash 在该页面底部有一个相对简单的实现:
#import <objc/runtime.h>
#import <objc/message.h>
//....
void Swizzle(Class c, SEL orig, SEL new)
{
Method origMethod = class_getInstanceMethod(c, orig);
Method newMethod = class_getInstanceMethod(c, new);
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);
}
I have not tested this, simply because I regard method swizzling as an extremely dangerous process and haven't had the need to use it yet.
我没有测试过这个,仅仅是因为我认为方法调配是一个极其危险的过程,还没有必要使用它。

