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

  1. @protocol MyProtocol  
  2.   
  3. - (void) doSomething;  
  4.   
  5. @end  
  6.   
  7. @interface MyClass : NSObject<MyProtocol>//直接符合协议的类  
  8. {  
  9. }  
  10.   
  11. @end  
  12.   
  13. @implementation MyClass  
  14.   
  15. - (void) doSomething {   
  16. }  
  17.   
  18. @end  
  19.   
  20. @interface MyOtherClass : MyClass//继承了符合协议的类,即其父类符合协议。  
  21. {  
  22.   
  23. }  
  24.   
  25. @end  
  26.   
  27. @implementation MyOtherClass  
  28.   
  29. - (void) doSomething {  
  30. }  
  31.   
  32. @end  
  33.   
  34.   
  35. int main (int argc, const char * argv[])   
  36. {  
  37.     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];  
  38.   
  39.     MyClass *obj_one = [MyClass new];  
  40.     BOOL one_conforms = [obj_one conformsToProtocol:@protocol(MyProtocol)];  
  41.   
  42.     MyOtherClass *obj_two = [MyOtherClass new];  
  43.   
  44.     //obj_two是类的实例对象,和父类相关,其父类符合协议,则其亦符合。  
  45.   
  46.     BOOL two_conforms = [obj_two conformsToProtocol:@protocol(MyProtocol)];  
  47.     NSLog(@"obj_one conformsToProtocol: %d", one_conforms);//output:YES   
  48.     NSLog(@"obj_two conformsToProtocol: %d", two_conforms);//output:YES   
  49.     [pool drain]; return 0;  
  50. }  
  51.   
  52. //Output:  
  53.     obj_one conformsToProtocol: 1  
  54.     obj_two conformsToProtocol: 1  
  55.   
  56. //Whereas:  
  57.      MyOtherClass *obj_two = [MyOtherClass new];  
  58.      //class_conformsToProtocol是只检查当前类符不符合协议,和其父类无关。  
  59.      BOOL conforms_two = class_conformsToProtocol([obj_two class], @protocol(MyProtocol));  
  60.      NSLog(@"obj_two conformsToProtocol: %d", conforms_two);//output:NO  
  61.   
  62. //Output:  
  63.      obj_two conformsToProtocol: 0  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值