昨天开会大家讨论了这个问题~但是没达搞清楚~私底下查查看吧~网上搜到的结果,当做笔记,记在这里,希望方便以后自己或者大家前来回顾、
- <pre name="code" class="cpp">//conformsToProtocol:@protocol()是用来检查对象是否实现了指定协议类的方法
- //例子如下,在例子当中会有适当的注释,以助理解这个方法:
- @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 *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</pre><span style="color:#CC0000">在代理调用是,检查其代理是否符合协议,或者使用 respondsToSelector 检查对象能否响应指定的消息,<br>
- 是避免代理在回调时因为没有实现代理函数而程序崩溃的一个有效的方式</span>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>