方法在iPhone设备上Swizzle

diz*_*izy 25 iphone objective-c swizzling

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

有没有人在iPhone上乱跑?什么诀窍?

TIA

Bra*_*son 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);
}
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢你的工作.使用它的关键是#import <objc/runtime.h> #import <objc/message.h> (3认同)
  • 在为单元测试构建模拟框架时,Swizzling非常有用. (3认同)