2010-07-16 12 views
29

विधि स्विजलिंग उदाहरण विधियों के लिए बहुत अच्छा काम करता है। अब, मुझे एक क्लास विधि स्विज करने की जरूरत है। कोई विचार यह कैसे करना है?आईओएस पर क्लास विधि कैसे घुमाएं?

इस की कोशिश की, लेकिन यह काम नहीं करता है:

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

एमएमएम ... मान लें कि हमने 'क्लास सीसी = ऑब्जेक्ट_get क्लास (आईडी) सी) ''। यह समझ में आता है कि आपको 'सीसी' में विधि जोड़ने की जरूरत है, लेकिन आपने क्लास विधि को' सीसी' से क्यों लिया? क्या आपको क्लास विधि 'सी' से नहीं मिलनी चाहिए? मैं उलझन में हूं ... – Yuji

+0

यूही, आप सही हैं, मैंने मूल वर्ग पर विधि संकल्प करने के लिए कोड बदल दिया है, मेटा क्लास नहीं। पुराना समाधान भी काम करता था इसलिए मैंने वास्तव में परेशान नहीं किया। –

+0

मेरा बुरा। मैं object_getClass objc_getClass में गलत टाइप किया। मैं एक सेकंड में अपना जवाब हटा दूंगा। –

संबंधित मुद्दे