object-c学习:协议 Protocol

 

在Object-C中,委托和数据源都是由协议实现的。协议定义了一个类与另一个类进行沟通的先验方式。

它们包含一个方法列表,有些是必须被实现的,有些是可选的。

任何实现了必需方法的类都被认为符合协议。

 

1、定义协议

定义协议的方式与定义类的类的方式非常相似。

  1. @protocol MyProtocol <NSObject>      
  2. - (void)firstMethod;      
  3. - (void)secondMethod;  
  4. @end  

2、定义一个类

这个类,本应实现firstMethod 和 secondMethod 方法,但是由于各种原因,并没有直接实现。

而是先这两个函数的功能“承包”给另外一个类(也就是代理)

 

  1. //.h   
  2. @interface MyClass : NSObject {      
  3. id <MyProtocol> delegate;  
  4. }  
  5. - (void)oneMethod;  
  6. @end  
  7.   
  8. //.m   
  9. @implementation MyClass  
  10. - (void)oneMethod {      
  11.     if(!delegate) {          
  12.         return;      
  13.     }  
  14.   
  15.     int type = random() % 10;      
  16.     if(type < 5){          
  17.         [self.delegate firstMethod];      
  18.     } else {         
  19.         [self.delegate secondMethod];      
  20.     }  
  21. }  
  22. @end  

    3、符合协议

    该类实现了firstMethod 和secondMethod 方法,符合MyProtocol

    1. @interface MyClassController : UIViewController <MyProtocol> {     
    2.     MyClass *myClass;  
    3. }  
    4.   
    5. @property [retain, nonatomic] MyClass *myClass;  
    6. @end  

      必须在该类的实现文件中,实现firstMethod 和 secondMethod方法,否则编译器会给出警告。

      然后,通过如下代码设置代理:

      1. self.myClass = [[MyClass alloc] init];  
      2. self.myClass.delegate = self;  

       

      • 0
        点赞
      • 1
        收藏
        觉得还不错? 一键收藏
      • 0
        评论

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

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

      请填写红包祝福语或标题

      红包个数最小为10个

      红包金额最低5元

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

      抵扣说明:

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

      余额充值