問題的背景
IOS中委托模式和消息機(jī)制基本上開發(fā)中用到的比較多,一般最開始頁面?zhèn)髦低ㄟ^委托實(shí)現(xiàn)的比較多,類之間的傳值用到的比較多,不過委托相對(duì)來說只能是一對(duì)一,比如說頁面A跳轉(zhuǎn)到頁面B,頁面的B的值改變要映射到頁面A,頁面C的值改變也需要映射到頁面A,那么就需要需要兩個(gè)委托解決問題。NSNotificaiton則是一對(duì)多注冊(cè)一個(gè)通知,之后回調(diào)很容易解決以上的問題。
概念
iOS消息通知機(jī)制算是同步的,觀察者只要向消息中心注冊(cè), 即可接受其他對(duì)象發(fā)送來的消息,消息發(fā)送者和消息接受者兩者可以互相一無所知,完全解耦。這種消息通知機(jī)制可以應(yīng)用于任意時(shí)間和任何對(duì)象,觀察者可以有多個(gè),所以消息具有廣播的性質(zhì),只是需要注意的是,觀察者向消息中心注冊(cè)以后,在不需要接受消息時(shí)需要向消息中心注銷,屬于典型的觀察者模式。
消息通知中重要的兩個(gè)類:
(1)NSNotificationCenter: 實(shí)現(xiàn)NSNotificationCenter的原理是一個(gè)觀察者模式,獲得NSNotificationCenter的方法只有一種,那就是[NSNotificationCenter defaultCenter] ,通過調(diào)用靜態(tài)方法defaultCenter就可以獲取這個(gè)通知中心的對(duì)象了。NSNotificationCenter是一個(gè)單例模式,而這個(gè)通知中心的對(duì)象會(huì)一直存在于一個(gè)應(yīng)用的生命周期。
(2) NSNotification: 這是消息攜帶的載體,通過它,可以把消息內(nèi)容傳遞給觀察者。
使用
1.通過NSNotificationCenter注冊(cè)通知NSNotification,viewDidLoad中代碼如下:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationFirst:) name:@"First" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationSecond:) name:@"Second" object:nil];
第一個(gè)參數(shù)是觀察者為本身,第二個(gè)參數(shù)表示消息回調(diào)的方法,第三個(gè)消息通知的名字,第四個(gè)為nil表示表示接受所有發(fā)送者的消息~
回調(diào)方法:
-(void)notificationFirst:(NSNotification *)notification{
NSString *name=[notification name];
NSString *object=[notification object];
NSLog(@"名稱:%@----對(duì)象:%@",name,object);
}
-(void)notificationSecond:(NSNotification *)notification{
NSString *name=[notification name];
NSString *object=[notification object];
NSDictionary *dict=[notification userInfo];
NSLog(@"名稱:%@----對(duì)象:%@",name,object);
NSLog(@"獲取的值:%@",[dict objectForKey:@"key"]);
}
2.消息傳遞給觀察者
[[NSNotificationCenter defaultCenter] postNotificationName:@"First" object:@"博客園-Fly_Elephant"];
NSDictionary *dict=[[NSDictionary alloc]initWithObjects:@[@"keso"] forKeys:@[@"key"]];
[[NSNotificationCenter defaultCenter] postNotificationName:@"Second" object:@"http://www.cnblogs.com/xiaofeixiang" userInfo:dict];
3.銷毀觀察者
-(void)dealloc{
NSLog(@"觀察者銷毀了");
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
也可以通過name單個(gè)刪除:
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"First" object:nil];
4.運(yùn)行結(jié)果
2015-04-26 15:08:25.900 CustoAlterView[2169:148380] 觀察者銷毀了
2015-04-26 15:08:29.222 CustoAlterView[2169:148380] 名稱:First----對(duì)象:博客園-Fly_Elephant
2015-04-26 15:08:29.222 CustoAlterView[2169:148380] 名稱:Second----對(duì)象:http://www.cnblogs.com/xiaofeixiang
2015-04-26 15:08:29.223 CustoAlterView[2169:148380] 獲取的值:keso
深入分析觀察者
如果想讓對(duì)象監(jiān)聽某個(gè)通知,則需要在通知中心中將這個(gè)對(duì)象注冊(cè)為通知的觀察者。早先,NSNotificationCenter提供了以下方法來添加觀察者:
- (void)addObserver:(id)notificationObserver selector:(SEL)notificationSelector name:(NSString *)notificationName object:(id)notificationSender
這個(gè)方法帶有4個(gè)參數(shù),分別指定了通知的觀察者、處理通知的回調(diào)、通知名及通知的發(fā)送對(duì)象。這里需要注意幾個(gè)問題
- notificationObserver不能為nil。
- notificationSelector回調(diào)方法有且只有一個(gè)參數(shù)(NSNotification對(duì)象)。
- 如果notificationName為nil,則會(huì)接收所有的通知(如果notificationSender不為空,則接收所有來自于notificationSender的所有通知)。如代碼清單1所示。
- 如果notificationSender為nil,則會(huì)接收所有notificationName定義的通知;否則,接收由notificationSender發(fā)送的通知。
- 監(jiān)聽同一條通知的多個(gè)觀察者,在通知到達(dá)時(shí),它們執(zhí)行回調(diào)的順序是不確定的,所以我們不能去假設(shè)操作的執(zhí)行會(huì)按照添加觀察者的順序來執(zhí)行。
對(duì)于以上幾點(diǎn),我們來重點(diǎn)關(guān)注一下第3條。以下代碼演示了當(dāng)我們的notificationName設(shè)置為nil時(shí),通知的監(jiān)聽情況。
測試代碼如下
添加一個(gè)Observer,其中notificationName為nil
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:nil object:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil];
}
- (void)handleNotification:(NSNotification *)notification
{
NSLog(@"notification = %@", notification.name);
}
@end
運(yùn)行后的輸出結(jié)果如下:
notification = TestNotification
notification = UIWindowDidBecomeVisibleNotification
notification = UIWindowDidBecomeKeyNotification
notification = UIApplicationDidFinishLaunchingNotification
notification = _UIWindowContentWillRotateNotification
notification = _UIApplicationWillAddDeactivationReasonNotification
notification = _UIApplicationDidRemoveDeactivationReasonNotification
notification = UIDeviceOrientationDidChangeNotification
notification = _UIApplicationDidRemoveDeactivationReasonNotification
notification = UIApplicationDidBecomeActiveNotification
可以看出,我們的對(duì)象基本上監(jiān)聽了測試程序啟動(dòng)后的所示消息。當(dāng)然,我們很少會(huì)去這么做。
而對(duì)于第4條,使用得比較多的場景是監(jiān)聽UITextField的修改事件,通常我們?cè)谝粋€(gè)ViewController中,只希望去監(jiān)聽當(dāng)前視圖中的UITextField修改事件,而不希望監(jiān)聽所有UITextField的修改事件,這時(shí)我們就可以將當(dāng)前頁面的UITextField對(duì)象指定為notificationSender。
NSNotification Block
在iOS 4.0之后,NSNotificationCenter為了跟上時(shí)代,又提供了一個(gè)以block方式實(shí)現(xiàn)的添加觀察者的方法,如下所示:
- (id<NSObject>)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block
大家第一次看到這個(gè)方法時(shí)是否會(huì)有這樣的疑問:觀察者呢?參數(shù)中并沒有指定具體的觀察者,那誰是觀察者呢?實(shí)際上,與前一個(gè)方法不同的是,前者使用一個(gè)現(xiàn)存的對(duì)象作為觀察者,而這個(gè)方法會(huì)創(chuàng)建一個(gè)匿名的對(duì)象作為觀察者(即方法返回的id<NSObject>對(duì)象),這個(gè)匿名對(duì)象會(huì)在指定的隊(duì)列(queue)上去執(zhí)行我們的block。
這個(gè)方法的優(yōu)點(diǎn)在于添加觀察者的操作與回調(diào)處理操作的代碼更加緊湊,不需要拼命滾動(dòng)鼠標(biāo)就能直接找到處理代碼,簡單直觀。這個(gè)方法也有幾個(gè)地方需要注意:
- name和obj為nil時(shí)的情形與前面一個(gè)方法是相同的。
- 如果queue為nil,則消息是默認(rèn)在post線程中同步處理,即通知的post與轉(zhuǎn)發(fā)是在同一線程中;但如果我們指定了操作隊(duì)列,情況就變得有點(diǎn)意思了,我們一會(huì)再講。
- block塊會(huì)被通知中心拷貝一份(執(zhí)行copy操作),以在堆中維護(hù)一個(gè)block對(duì)象,直到觀察者被從通知中心中移除。所以,應(yīng)該特別注意在block中使用外部對(duì)象,避免出現(xiàn)對(duì)象的循環(huán)引用,這個(gè)我們?cè)谙旅鎸⑴e例說明。
- 如果一個(gè)給定的通知觸發(fā)了多個(gè)觀察者的block操作,則這些操作會(huì)在各自的Operation Queue中被并發(fā)執(zhí)行。所以我們不能去假設(shè)操作的執(zhí)行會(huì)按照添加觀察者的順序來執(zhí)行。
- 該方法會(huì)返回一個(gè)表示觀察者的對(duì)象,記得在不用時(shí)釋放這個(gè)對(duì)象。
下面我們重點(diǎn)說明一下第2點(diǎn)和第3點(diǎn)。
關(guān)于第2點(diǎn),當(dāng)我們指定一個(gè)Operation Queue時(shí),不管通知是在哪個(gè)線程中post的,都會(huì)在Operation Queue所屬的線程中進(jìn)行轉(zhuǎn)發(fā):
代碼如下:
在指定隊(duì)列中接收通知
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserverForName:TEST_NOTIFICATION object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
NSLog(@"receive thread = %@", [NSThread currentThread]);
}];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"post thread = %@", [NSThread currentThread]);
[[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil];
});
}
@end
在這里,我們?cè)谥骶€程里添加了一個(gè)觀察者,并指定在主線程隊(duì)列中去接收處理這個(gè)通知。然后我們?cè)谝粋€(gè)全局隊(duì)列中post了一個(gè)通知。我們來看下輸出結(jié)果:
post thread = <NSThread: 0x7ffe0351f5f0>{number = 2, name = (null)}
receive thread = <NSThread: 0x7ffe03508b30>{number = 1, name = main}
可以看到,消息的post與接收處理并不是在同一個(gè)線程中。如上面所提到的,如果queue為nil,則消息是默認(rèn)在post線程中同步處理,大家可以試一下。
對(duì)于第3點(diǎn),由于使用的是block,所以需要注意的就是避免引起循環(huán)引用的問題,如下:
block引發(fā)的循環(huán)引用問題
@interface Observer : NSObject
@property (nonatomic, assign) NSInteger i;
@property (nonatomic, weak) id<NSObject> observer;
@end
@implementation Observer
- (instancetype)init
{
self = [super init];
if (self)
{
NSLog(@"Init Observer");
// 添加觀察者
_observer = [[NSNotificationCenter defaultCenter] addObserverForName:TEST_NOTIFICATION object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
NSLog(@"handle notification");
// 使用self
self.i = 10;
}];
}
return self;
}
@end
·#pragma mark - ViewController
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self createObserver];
// 發(fā)送消息
[[NSNotificationCenter defaultCenter] postNotificationName:TEST_NOTIFICATION object:nil];
}
- (void)createObserver {
Observer *observer = [[Observer alloc] init];
}
@end
運(yùn)行后的輸出如下:
Init Observer
handle notification
我們可以看到createObserver中創(chuàng)建的observer并沒有被釋放。所以,使用 – addObserverForName:object:queue:usingBlock:一定要注意這個(gè)問題。