1. 发出通知:
//postNotificationName:给发送的通知起一个名字
//object:
一般可以为nil,如果为self就是把当前controller传递给监听者
//userInfo:传递需要的数据,用key:value的形式把数据封装在字典里边,传递给监听者
[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationNameChangeLabelText object:self userInfo:@{@"text" : self.textField.text}];
2. 接收通知
//addObserver:
注册监听者,一般都是Controller本身去监听通知
//selector:当监听到通知的时候执行的方法
//name:通知的名字,要和发送通知的对象的名字一致
//selector:当监听到通知的时候执行的方法
//name:通知的名字,要和发送通知的对象的名字一致
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeLabelText:) name:kNotificationNameChangeLabelText
object:nil];
3. 实现通知方法:
- (void)changeLabelText:(NSNotification
*)notification {
NSDictionary *dic = notification.userInfo;
self.label.text = dic[@"text"];
//移除RootViewController上所有监听的通知
[[NSNotificationCenter defaultCenter] removeObserver:self];
NSDictionary *dic = notification.userInfo;
self.label.text = dic[@"text"];
//移除RootViewController上所有监听的通知
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
本文详细介绍了如何在iOS应用中使用通知中心来实现组件间的解耦通讯。包括如何发送通知、接收通知及实现通知方法等内容,并附带了具体的代码示例。
586

被折叠的 条评论
为什么被折叠?



