通知,Block,代理

OC中经常要用到一些事件和参数的传递,通常有三种做法:通知 代理 Block

通知可以一对多,代理

通知

1. 发送通知

NSDictionary *dict =[[NSDictionary alloc] initWithObjectsAndKeys:@(self.currentRow),@"cellRow", nil];

//创建通知
NSNotification *notification =[NSNotification notificationWithName:@"ChangeBuyAddShopCartBtnClick" object:nil userInfo:dict];//如果不需要传递参数
    
//通过通知中心发送通知
[[NSNotificationCenter defaultCenter] postNotification:notification];

2.注册通知

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(todayTeamBuy)name:@"ChangeBuyAddShopCartBtnClick"object:nil];

并在 @selector(todayTeamBuy) 方法中实现你想要的动作

3. 拿到通知传递的参数和调用的方法

- (void)todayTeamBuy:(NSNotification *)noti
{
      NSDictionary *dataDic = noti.userInfo;//通知传递的参数
}

4.在dealloc中注销通知

[[NSNotificationCenter defaultCenter] removeObserver:self];



Block

1.逆传数据  (A是B 的父控制器  , B点击按钮改变Label)

B.h

//传值:需要传值的时候,再去调用

@property(nonatomic,strong)void(^valueBlcok)(NSString*str);



B.m

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event

{

//传值给ViewController

//调用代理方法传值

//if ([_delegate respondsToSelector:@selector(modalViewController:clickScreen:)]) {

//[_delegate modalViewController:self clickScreen:@"123"];

//}

//传值:调用block

if(_valueBlcok) {

_valueBlcok(@"123");

}

}

代理

当A做什么事情不方便的时候,建立一个委托,委托B帮自己去实现方法。这种模式叫作协议 委托,B就是A 的代理.
常见的有UITableView.delegate


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容