conformsToProtocol:@protocol()是用来检查对象是否实现了指定协议类的方法
class_conformsToProtocol是只检查当前类符不符合协议,和其父类无关
举例如下:
@protocol MyProtocol
- (void)doSomeThing;
@end
@interface MyClass : NSObject <MyProtocol>
{
}
@end
@implementation MyClass
- (void)doSomeThing {
};
@end
@interface MyOtherClass : MyClass
{
}
@end
@implementation MyOtherClass
- (void)doSomeThing {
};
@end
int main (int argc, const char* argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
MyClass *class_one = [MyClass new];
Bool conforms_one = [class_one conformsToProtocol:@protocol(MyProtocol)];
MyOtherClass *class_two = [MyOtherClass new];
Bool conforms_two = [class_two conformsToProtocol:@protocol(MyProtocol)];
NSLog(@"class_one conformsToProtocol: %d", conforms_one); // output: YES
NSLog(@"class_two conformsToProtocol: %d", conforms_two); // output: YES
Bool conforms_three = class_conformsToProtocol([class_two class], @protocol(MyProtocol));
NSLog(@"conforms_two class_conformsToProtocol: %d", conforms_three); // output: NO
}