conformsToProtocol:@protocol()的理解和用法

转自Linlei的专栏

//conformsToProtocol:@protocol()是用来检查对象是否实现了指定协议类的方法  //例子如下,在例子当中会有适当的注释,以助理解这个方法:    

@protocol MyProtocol   

 - (void) doSomething;    

@end   

 @interface MyClass : NSObject//直接符合协议的类

{

}

@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 *obj_one = [MyClass new];

BOOL one_conforms = [obj_one conformsToProtocol:@protocol(MyProtocol)];

MyOtherClass *obj_two = [MyOtherClass new];

//obj_two是类的实例对象,和父类相关,其父类符合协议,则其亦符合。

BOOL two_conforms = [obj_two conformsToProtocol:@protocol(MyProtocol)];

NSLog(@"obj_one conformsToProtocol: %d", one_conforms);//output:YES

NSLog(@"obj_two conformsToProtocol: %d", two_conforms);//output:YES

[pool drain]; return 0;

}

//Output:

obj_one conformsToProtocol: 1

obj_two conformsToProtocol: 1

//Whereas:

MyOtherClass *obj_two = [MyOtherClass new];

//class_conformsToProtocol是只检查当前类符不符合协议,和其父类无关。

BOOL conforms_two = class_conformsToProtocol([obj_two class], @protocol(MyProtocol));

NSLog(@"obj_two conformsToProtocol: %d", conforms_two);//output:NO

//Output:

obj_two conformsToProtocol: 0

在代理调用是,检查其代理是否符合协议,或者使用 respondsToSelector 检查对象能否响应指定的消息,

是避免代理在回调时因为没有实现代理函数而程序崩溃的一个有效的方式

你可能感兴趣的:(conformsToProtocol:@protocol()的理解和用法)