25

我尝试了 JRSwizzle 和 MethodSwizzle。它们在模拟器上编译得很好,但是当我尝试为 Device (3.x) 编译时抛出一堆错误

有没有人在iphone上玩过运气?有什么诀窍?

TIA

4

1 回答 1

55

CocoaDev wiki 在这里对方法调配进行了广泛的讨论。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);
}

我没有对此进行测试,仅仅是因为我认为方法调配是一个极其危险的过程,并且还没有使用它的需要。

于 2009-10-28T17:53:31.023 回答