NSNotification 的3種使用方式
-
1孙乖、不傳遞參數(shù), 最常用的一種
// 發(fā)送通知
-(void)btn1Click{
[[NSNotificationCenter defaultCenter] postNotificationName:@"notifyName1" object:nil];
}
//注冊通知(接收,監(jiān)聽,一個通知)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification1) name:@"notifyName1" object:nil];
//實現(xiàn)方法
-(void)notification1{
NSLog(@"接收 不帶參數(shù)的消息");
}
- 2竿屹、使用object 傳遞消息
//發(fā)通知
-(void)btn2Click:(UIButton *)btn{
[[NSNotificationCenter defaultCenter] postNotificationName:@"notifyName2" object:[NSString stringWithFormat:@"%@",btn.titleLabel.text]];
}
//注冊通知(接收,監(jiān)聽,一個通知)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification2:) name:@"notifyName2" object:nil];
//實現(xiàn)方法
-(void)notification2:(NSNotification *)noti{
//使用object處理消息
NSString *info = [noti object];
NSLog(@"接收 object傳遞的消息:%@",info);
}
- 3吊履、使用userInfo 傳遞消息
//發(fā)通知
-(void)btn3Click{
NSDictionary *dic = [NSDictionary dictionaryWithObject:@"userInfo消息" forKey:@"param"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"nitifyName3" object:nil userInfo:dic];
}
//注冊通知(接收,監(jiān)聽,一個通知)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification3:) name:@"nitifyName3" object:nil];
//實現(xiàn)方法
-(void)notification3:(NSNotification *)noti{
//使用userInfo處理消息
NSDictionary *dic = [noti userInfo];
NSString *info = [dic objectForKey:@"param"];
NSLog(@"接收 userInfo傳遞的消息:%@",info);
}
最后甥温,在[接收]消息的頁面励堡,在dealloc方法里面移除觀察者米碰。
-(void)dealloc{
//移除觀察者
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
-
[拓展] 在一個大的項目中, 由于通知較多, 一般建立一個文件統(tǒng)一管理通知名, 通知名定義為常量
- NotifyConst.h
#import <Foundation/Foundation.h>
// extern : 引用本類或者其他類中使用
// xxA類通知
extern NSString *const NotifyName1;
extern NSString *const NotifyName2;
// xxB類通知
extern NSString *const xxx
extern NSString *const xxx
//xxC類通知
extern NSString *const xxx;
- NotifyConst.m
/**
常量值
.m 文件中進行賦值 const:標識后面的東西是不可修改的
*/
// xxA類通知
NSString *const NotifyName1 = @"NotifyName1";
NSString *const NotifyName2 = @"NotifyName2";
// xxB類通知
NSString *const xxx = ...'
NSString *const xxx = ....
最后, 在pch文件中加入NotifyConst.h就行了