??通知中心(NSNotificationCenter)是在程序內(nèi)部提供了一種廣播機(jī)制,可以一對多的發(fā)送通知,通知的使用步驟:創(chuàng)建通知、發(fā)送通知、移除通知,創(chuàng)建通知有兩種方法,分別為[NSNotificationCenter defaultCenter] addObserver
和[NSNotificationCenter defaultCenter] addObserverForName:
,首先介紹下第一種方法:
??一般最好在viewDidLoad的方法中創(chuàng)建通知,因?yàn)樵摲椒ㄖ蛔咭淮?,防止多次?chuàng)建
??1、創(chuàng)建通知
- (void)viewDidLoad {
[super viewDidLoad];
//創(chuàng)建通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(respond:) name:@"tongzhi" object:nil];
}
//實(shí)現(xiàn)響應(yīng)
- (void)respond:(NSNotification *)notification{
//通知內(nèi)容
NSDictionary *dic = notification.object;
}
??2、發(fā)送通知
//發(fā)送通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"tongzhi" object:nil];
??當(dāng)然你可以傳遞一些自己封裝的數(shù)據(jù),通過object就行,如:
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"松",@"name",@"男",@"sex", nil];
//發(fā)送通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"tongzhi" object:dic];
??3、移除通知
??移除通知一般在dealloc中實(shí)現(xiàn),因?yàn)樵絹碓蕉鄳?yīng)用支持手勢返回,滑回一半又返回等操作,在頁面真正銷毀的時(shí)候移除最好
??移除有兩種方法,一個(gè)是移除當(dāng)前頁面所有的通知,還有一種移除指定的通知,具體用哪個(gè)看實(shí)際情況,如下:
-(void)dealloc{
// 移除當(dāng)前所有通知
[[NSNotificationCenter defaultCenter] removeObserver:self];
//移除名為tongzhi的那個(gè)通知
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"tongzhi" object:nil];
}
??注意:dealloc方法不走一般原因有三個(gè):
1、ViewController中存在NSTimer ,計(jì)時(shí)器是否銷毀;
2、ViewController中有關(guān)的代理 ,要記住delegate的屬性應(yīng)該是assign;
3、ViewController中有Block,Block里面是否有強(qiáng)引用;
?? 下面介紹第二種使用的通知方法:
??1、創(chuàng)建通知
??這個(gè)方法需要一個(gè)id類型的值接受
@property (nonatomic, weak) id observe;
??再創(chuàng)建通知
//Name: 通知的名稱
//object:誰發(fā)出的通知
//queue: 隊(duì)列,決定 block 在哪個(gè)線程中執(zhí)行, nil 在發(fā)布通知的線程中執(zhí)行
//usingBlock: 只要監(jiān)聽到通知,就會(huì)執(zhí)行這個(gè) block
_observe = [[NSNotificationCenter defaultCenter] addObserverForName:@"tongzhi" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
NSLog(@"收到了通知");
}];
??該方法有個(gè)block,要操作的步驟可以直接寫在block里面,代碼的可讀比第一種高,所以用的人更多
??2、發(fā)送通知
//與第一種發(fā)送通知一樣
[[NSNotificationCenter defaultCenter] postNotificationName:@"tongzhi" object:nil];
??3、移除通知
- (void)dealloc {
//移除觀察者 _observe
[[NSNotificationCenter defaultCenter] removeObserver:_observe];
}
??從移除的方法,應(yīng)該知道了,為什么第二種創(chuàng)建通知方法時(shí)要有一個(gè)id類型的值接受,千萬不要用第一種的注銷方法,這也是我用錯(cuò)了的原因,我創(chuàng)建的時(shí)候沒用一個(gè)值接收,直接這么寫:
[[NSNotificationCenter defaultCenter] addObserverForName:@"tongzhi" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
NSLog(@"收到了通知");
}];
??導(dǎo)致通知未移除而重復(fù)創(chuàng)建,執(zhí)行方法一次比一次多,而移除的時(shí)候用
-(void)dealloc{
//用第二種創(chuàng)建方法錯(cuò)誤的移除
//移除名為tongzhi的那個(gè)通知
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"tongzhi" object:nil];
}
??從而導(dǎo)致程序出問題,還有一點(diǎn)值得注意的是,銷毀應(yīng)該是哪里創(chuàng)建哪里銷毀,不要在發(fā)送的控制器里執(zhí)行銷毀!!
聲明: 轉(zhuǎn)載請注明出處http://www.lxweimin.com/p/ab52ee91cbb0