2014-02-13 39 views
4

如果一個對象符合Objective-C中的某個協議,是否有辦法檢查它是否符合該協議中的所有方法。我寧願避免明確檢查每種可用的方法。如何檢查一個類是否在Obj-C中實現了協議中的所有方法?

感謝

+2

協議方法在缺省情況下是必需的,所以如果一個類採用給定的協議,它應該實現所有那些未標記爲「@option」的方法al'。 – Caleb

+1

@NoahWitherspoon我不問如何檢查協議的一致性。我在問如何檢查實際協議中的方法是否全部實現。 – cgossain

+2

也許通過一個爲協議的每種方法調用respondsToSelector的循環。並有協議的方法,請查看http://stackoverflow.com/questions/2094702/get-all-methods-of-an-objective-c-class-or-instance – Johnmph

回答

5

你可以得到與protocol_copyMethodDescriptionList的協議,它返回一個指向objc_method_description結構聲明的所有方法。

objc_method_descriptionobjc/runtime.h定義:

struct objc_method_description { 
    SEL name;    /**< The name of the method */ 
    char *types;   /**< The types of the method arguments */ 
}; 

要找出是否要選擇一類響應的情況下使用instancesRespondToSelector:

具有這樣的功能離開你:

BOOL ClassImplementsAllMethodsInProtocol(Class class, Protocol *protocol) { 
    unsigned int count; 
    struct objc_method_description *methodDescriptions = protocol_copyMethodDescriptionList(protocol, NO, YES, &count); 
    BOOL implementsAll = YES; 
    for (unsigned int i = 0; i<count; i++) { 
     if (![class instancesRespondToSelector:methodDescriptions[i].name]) { 
      implementsAll = NO; 
      break; 
     } 
    } 
    free(methodDescriptions); 
    return implementsAll; 
} 
+1

內存泄漏如果類沒有實現協議的所有方法,請添加free(methodDescrptions);在返回之前NO;或者甚至更好的添加一個標誌,並在找不到時打破循環。 – Johnmph

+0

夥計們一個字......壞蛋。感謝塞巴斯蒂安爲這個令人敬畏的答案,並感謝@Johhnmph的後續評論。 – cgossain

+0

@Johhnmph謝謝,趕上!我更新了我對單個回報聲明的回答。 – Sebastian

相關問題