iOS 通知NSNotifition

NOtifition (通知中心)

是成对出现的 : 有注册 就有释放

在 dealloc 方法中进行释放

1.Notifition 的规范

在 .h 文件中

import <UIKit/UIKit.h>

//通知名定义
extern NSString *const kNotifition;

在 .m 文件中

import "ViewController.h"

NSString *const kStartNotifition = @"kStartNotifition";

注意:每一个程序都有一个自己的通知中心,即NSNotificationCenter对象。该对象采用单例设计模式,采用defaultCenter方法就可以获得唯一的NSNotificationCenter对象。

2.注册通知:addObserver:selector:name:object:
//注册通知NSNotificationCenter
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeColor) name:@"color" object:nil];

3.发送通知:postNotificationName:object:或者performSelectorOnMainThread:withObject:waitUntilDone:
//发送消息
[[NSNotificationCenter defaultCenter] postNotificationName:@"color" object:nil];

object: 后可以用来 传值,(所谓的通知传值)

通知都是唯一的,通过 name: 来区分是哪个通知

4.移除通知:removeObserver:和removeObserver:name:object:
[[NSNotificationCenter defaultCenter] removeObserver:observer name:@"color" object:self];
在dealloc方法中移除

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

推荐阅读更多精彩内容