conformsToProtocol:@protocol()的理解和用法
来源:互联网 发布:kako女装淘宝旗舰店 编辑:程序博客网 时间:2024/05/17 06:26
- <pre name="code" class="cpp">
-
-
- @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];
-
-
-
- BOOL two_conforms = [obj_two conformsToProtocol:@protocol(MyProtocol)];
- NSLog(@"obj_one conformsToProtocol: %d", one_conforms);
- NSLog(@"obj_two conformsToProtocol: %d", two_conforms);
- [pool drain]; return 0;
- }
-
-
- obj_one conformsToProtocol: 1
- obj_two conformsToProtocol: 1
-
-
- MyOtherClass *obj_two = [MyOtherClass new];
-
- BOOL conforms_two = class_conformsToProtocol([obj_two class], @protocol(MyProtocol));
- NSLog(@"obj_two conformsToProtocol: %d", conforms_two);
-
-
- obj_two conformsToProtocol: 0</pre><span style="color:#CC0000">在代理调用是,检查其代理是否符合协议,或者使用 respondsToSelector 检查对象能否响应指定的消息,<br>
- 是避免代理在回调时因为没有实现代理函数而程序崩溃的一个有效的方式</span>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>