Tag Archives: runtime

objc的运行时

很多时候,程序需要做统计,或者很多页面要做一样的功能,但又不能继承同一个基类

这个时候我想到了AOP,但objc做AOP好像没有太好的方法。

找到了如下一个方法,运行时替换,太爽了。

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

}