實例/類方法,判斷對象能否響應指定 Selector(含繼承方法)。常用於安全調用代理回調,避免未實現方法導致崩潰。
SEL sel = @selector(handleData:);
if ([delegate respondsToSelector:sel]) {
[delegate performSelector:sel withObject:data];
}
相關方法:isKindOfClass:(繼承關係)、isMemberOfClass:(精確類別)、instancesRespondToSelector:(類方法檢查實例)。
判斷對象(實例)是否遵循特定 @protocol,**包含繼承鏈**:子類實例若父類遵循協議,亦返回 YES。
@protocol MyProtocol
- (void)doSomething;
@end
@interface MyClass : NSObject <MyProtocol> @end
@implementation MyClass
- (void)doSomething {} @end
@interface MySubclass : MyClass @end // 繼承父類協議
@implementation MySubclass @end
MyClass *o1 = [MyClass new];
MySubclass *o2 = [MySubclass new];
[o1 conformsToProtocol:@protocol(MyProtocol)]; // YES
[o2 conformsToProtocol:@protocol(MyProtocol)]; // YES(繼承而來)
區別:class_conformsToProtocol 僅檢查當前類聲明,不看父類(上例 o2 類檢查返回 NO)。
代理調用前雙重保險:conformsToProtocol 確認協議完整性 + respondsToSelector 確認可選方法實現,最大程度避免回調崩潰。