如何调整iOS上的类方法?

问题描述:

方法swizzling工程很好,例如方法。现在,我需要调整类方法。任何想法如何做到这一点?如何调整iOS上的类方法?

试过,但它不工作:

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

事实证明,我当时就在不远处。这个实现适用于我:

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); 
} 
+0

嗯......比方说,我们改为'Class cc = object_getClass((id)c)'。可以理解的是,您需要将方法添加到'cc',但为什么要从'cc'中使用类方法?你不是应该从'c'获得类方法吗?我很困惑... – Yuji 2010-07-16 19:24:02

+0

Yuhi,你说得对,我已经改变了代码来做原始类的方法决议,而不是元类。旧的解决方案也起作用,所以我没有真正烦恼。 – 2010-07-20 08:00:53

+0

我的不好。我打错了object_getClass到objc_getClass中。我会在一秒钟内删除我的答案。 – 2014-12-01 15:00:20