NSNotificationCenter 的简单使用

来源:互联网 发布:淘宝上的开团提醒 编辑:程序博客网 时间:2024/05/16 15:20

1.先成为观察者(B)

B.h

- (void)becomeObserve;

B.m

- (void)becomeObserve {    // 在消息通知中心订阅一条名为“dataChange”的消息,当消息发出时,会通知 self调用selector中的方法 object如果设为nil,表示会收到所有这个名字的消息    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updataUI) name:@"dataChange" object:nil];}

2.发送通知(A)

A.m

    // 当数据发生变化时,需要将此消息发布出去(如果对象关心此消息就需要提前订阅)    // 去消息通知中心发送广播    [b <span style="font-family: Arial, Helvetica, sans-serif;">becomeObserve];<span style="white-space:pre"></span>// </span><span style="font-family: Arial, Helvetica, sans-serif;">b成为观察者</span><span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre"></span></span>    //第一个参数 消息的名称  第二个参数 发送消息的对象    //[[NSNotificationCenter defaultCenter] postNotificationName:@"dataChange" object:nil];        // 发布消息的同时传递数据,需要将数据封装成个字典    NSDictionary * dict = [NSDictionary dictionaryWithObjectsAndKeys:@"Kermit",@"name", nil];    [[NSNotificationCenter defaultCenter] postNotificationName:@"dataChange" object:nil userInfo:dict];

3.退订消息(不再成为观察者)

B.m

- (void)dealloc {    // 退订消息(不再成为观察者)当“dataChange”消息来到时不再关心,处理,object表示发出消息的对象    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"dataChange" object:nil];}


0 0
原创粉丝点击