zoukankan      html  css  js  c++  java
  • 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  
  • 相关阅读:
    自定义配置文件的使用
    网络编程入门建议
    SQL2005 表分区亲测
    数据库文件组小记
    eclipse 项目显示红叉
    Flex DataGrid可编辑对象实现Enter跳转
    excel 巧用功能
    ACCESS中查询语句:查询所得数据另存到一个指定目录下的文件夹里,并新建新的文件
    邮件合并 :处理ACCESS中批量查询语句的运行
    文件分类批处理程序
  • 原文地址:https://www.cnblogs.com/linyawen/p/2554834.html
Copyright © 2011-2022 走看看