2010-07-16 8 views
29

메서드 swizzling은 인스턴스 메서드에 적합합니다. 자, 클래스 메서드를 swizzle해야합니다. 어떤 생각을하는 방법? 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); 
} 

답변

53

밝혀, 나는 멀리하지 않았다. 이 구현은 나를 위해 작동합니다 :

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

+0

Yuhi, 네 말이 맞아, 나는 메타 클래스가 아니라 원래 클래스의 메소드 해상도를 변경했다. 이전 솔루션도 잘 작동 했으므로 신경 쓰지 않았습니다. –

+0

제 잘못입니다. object_getClass를 objc_getClass로 잘못 입력했습니다. 잠시 후에 내 대답을 삭제하겠습니다. –

관련 문제