通知NSNotificationCenter

添加通知

//UIColor *color;
//NSNotificationCenter  通知中心 ,单例类
//单例类:在整个应用程序中只有一个对象,调用单利方法是,不管创建多少次,都是同一个对象
//defaultCenter 时通知中心的单利方法
NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:color,@"color", nil];
//postNotificationName 发通知
//参数1.通知的名字2.由谁发送通知3.发通知是需要传递的参数
[notiCenter postNotificationName:@"changeColor" object:self userInfo:dic];

接收通知

//参数1.由谁去接收通知2.接收到通知后,需要执行的方法,如果方法需要传参,参数是NSNotification的对象3.接受通知的名字,要和发送通知时名字保持一致(调频一致);如果写nil,默认接受所有的通知4.是否指定通知的发送者,指定接受某一个对象发送的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiceChangeColorNotification:) name:@"changeColor" object:nil];

//接收到通知执行的方法
-(void)receiceChangeColorNotification:(NSNotification*)noti
{
//noti.name 通知的名字
//noti.object 通知的发送者
//noti.userInfo 发送通知传递的参数
NSLog(@"接受到了改变颜色的通知:%@__%@__%@",noti.name,noti.object,noti.userInfo);
NSDictionary *dic = noti.userInfo;
UIColor *color = [dic objectForKey:@"color"];
self.view.backgroundColor = color;
}

当给一个已经释放的对象(如一个自定义类)发送通知时 系统会立即崩溃 解决办法是 在自定义类的 dealloc 方法中移除通知

//移除通知
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"classOver" object:nil];

系统自带的通知

//应用程序进入到后台的通知
//UIApplicationDidEnterBackgroundNotification 程序进图后台的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationGotoBackGround) name:UIApplicationDidEnterBackgroundNotification object:nil];
//接受到键盘frame改变的通知
//UIKeyboardWillChangeFrameNotification 键盘frame将要改变的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容