如何在iOS上调整类方法? [英] How to swizzle a class method on iOS?
本文介绍了如何在iOS上调整类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
方法调配对于实例方法非常有用。现在,我需要调整一个类方法。知道怎么做吗?
Method swizzling works great for instance methods. Now, I need to swizzle a class method. Any idea how to do it?
试过这个但是不起作用:
Tried this but it doesn't work:
void SwizzleClassMethod(Class c, SEL orig, SEL new) {
Method origMethod = class_getClassMethod(c, orig);
Method newMethod = class_getClassMethod(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);
}
推荐答案
原来,我不是'很远的地方。这个实现对我有用:
Turns out, I wasn't far away. This implementation works for me:
void SwizzleClassMethod(Class c, SEL orig, SEL new) {
Method origMethod = class_getClassMethod(c, orig);
Method newMethod = class_getClassMethod(c, new);
c = object_getClass((id)c);
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);
}
这篇关于如何在iOS上调整类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文