Object-C 协议 Protocol

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

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

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

1、定义协议

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

@protocol MyProtocol <NSObject>    
- (void)firstMethod;    
- (void)secondMethod;
@end

2、定义一个类

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

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

//.h
@interface MyClass : NSObject {    
id <MyProtocol> delegate;
}
- (void)oneMethod;
@end

//.m
@implementation MyClass
- (void)oneMethod {    
    if(!delegate) {        
        return;    
    }

    int type = random() % 10;    
    if(type < 5){        
        [self.delegate firstMethod];    
    } else {       
        [self.delegate secondMethod];    
    }
}
@end

3、符合协议

该类实现了firstMethod 和secondMethod 方法,符合MyProtocol
@interface MyClassController : UIViewController <MyProtocol> {   
    MyClass *myClass;
}

@property [retain, nonatomic] MyClass *myClass;
@end

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

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

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值