NSNotificationCenter
對于這個沒必要多說,就是一個消息通知機制抑淫,類似廣播绷落。觀察者只需要向消息中心注冊感興趣的東西,當(dāng)有地方發(fā)出這個消息的時候始苇,通知中心會發(fā)送給注冊這個消息的對象砌烁。這樣也起到了多個對象之間解耦的作用。蘋果給我們封裝了這個NSNotificationCenter,讓我們可以很方便的進行通知的注冊和移除函喉。然而避归,有些人的姿勢還是有點小問題的,下面就看看正確的姿勢吧管呵!
正確姿勢之remove
只要往NSNotificationCenter注冊了梳毙,就必須有remove的存在,這點是大家共識的捐下。但是大家在使用的時候發(fā)現(xiàn)账锹,在UIViewController 中addObserver后沒有移除,好像也沒有掛坷襟!我想很多人可能和我有一樣的疑問奸柬,是不是因為使用了ARC?在你對象銷毀的時候自動置為nil了呢婴程?或者蘋果在實現(xiàn)這個類的時候用了什么神奇的方式呢廓奕?下面我們就一步步來探究下。
首先档叔,向NSNotificationCenter中addObserver后桌粉,并沒有對這個對象進行引用計數(shù)加1操作,所以它只是保存了地址蹲蒲。為了驗證這個操作番甩,我們來做下代碼的測試。
<p>一個測試類届搁,用來注冊通知:</p>
<pre><code>
<p>@implementation MRCObject</p>
-(id)init
{
if (self = [super init]) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test) name:@"test" object:nil];
}
return self;
}
-(void)test
{
NSLog(@"=================");
}
-(void)dealloc
{
[super dealloc];
}
@end</code></pre>
這個類很簡單缘薛,就是在初始化的時候,給他注冊一個通知卡睦。但是在銷毀的時候不進行remove操作宴胧。我們在VC中創(chuàng)建這個對象后,然后銷毀表锻,最后發(fā)送這個通知:
<p>這是一個普通段落:</p>
- (void)viewDidLoad
{
[super viewDidLoad];
MRCObject *obj = [[MRCObject alloc] init];
[obj release];
[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil];
進入這個VC后恕齐,我們發(fā)現(xiàn)掛了。瞬逊。打印的信息是:
2015-01-19 22:49:06.655 測試[1158:286268] *** -[MRCObject test]: message sent to deallocated instance 0x17000e5b0
我們可以發(fā)現(xiàn)显歧,向野指針對象發(fā)送了消息,所以掛掉了确镊。從這點來看士骤,蘋果實現(xiàn)也基本差不多是這樣的,只保存了個對象的地址蕾域,并沒有在銷毀的時候置為nil拷肌。
這點就可以證明到旦,addObserver后,必須要有remove操作巨缘。
現(xiàn)在我們在UIViewController中注冊通知添忘,不移除,看看會不會掛掉若锁。
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test) name:@"test" object:nil];
}
首先用navigationController進入到這個頁面搁骑,然后pop出去。最后點擊發(fā)送通知的按鈕事件:
- (void)didButtonClicked:(id)sender
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil];
}
無論你怎么點擊這個按鈕拴清,他就是不掛靶病!這下,是不是很郁悶了口予?我們可以找找看,你代碼里面沒有remove操作涕侈,但是NSNotificationCenter那邊已經(jīng)移除了沪停,不然肯定會出現(xiàn)上面野指針的問題∩烟危看來看去木张,也只能說明是UIViewController自己銷毀的時候幫我們暗地里移除了。
那我們?nèi)绾巫C明呢端三?由于我們看不到源碼舷礼,所以也不知道有沒有調(diào)用。這個時候郊闯,我們可以從這個通知中心下手F尴住!团赁!怎么下手呢育拨?我只要證明UIViewController在銷毀的時候調(diào)用了remove方法,就可以證明我們的猜想是對的了欢摄!這個時候熬丧,就需要用到我們強大的類別這個特性了。我們?yōu)镹SNotificationCenter添加個類別怀挠,重寫他的- (void)removeObserver:(id)observer方法:
- (void)removeObserver:(id)observer
{
NSLog(@"====%@ remove===", [observer class]);
}
這樣在我們VC中導(dǎo)入這個類別析蝴,然后pop出來,看看發(fā)生了什么绿淋!
2015-01-19 22:59:00.580 測試[1181:288728] ====TestViewController remove===
怎么樣闷畸?是不是可以證明系統(tǒng)的UIViewController在銷毀的時候調(diào)用了這個方法。(不建議大家在開發(fā)的時候用類別的方式覆蓋原有的方法躬它,由于類別方法具有更高的優(yōu)先權(quán)腾啥,所以有可能影響到其他地方。這里只是調(diào)試用)。
以上也提醒我們倘待,在你不是銷毀的時候疮跑,千萬不要直接調(diào)用[[NSNotificationCenter defaultCenter] removeObserver:self]; 這個方法,因為你有可能移除了系統(tǒng)注冊的通知凸舵。
正確姿勢之注意重復(fù)addObserver
在我們開發(fā)中祖娘,我們經(jīng)常可以看到這樣的代碼:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test) name:@"test" object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"test" object:nil];
}
就是在頁面出現(xiàn)的時候注冊通知啊奄,頁面消失時移除通知渐苏。你這邊可要注意了,一定要成雙成對出現(xiàn)菇夸,如果你只在viewWillAppear 中 addObserver沒有在viewWillDisappear 中 removeObserver那么當(dāng)消息發(fā)生的時候琼富,你的方法會被調(diào)用多次,這點必須牢記在心庄新。
正確姿勢之多線程通知
首先看下蘋果的官方說明:
Regular notification centers deliver notifications on the thread in which the notification was posted. Distributed notification centers deliver notifications on the main thread. At times, you may require notifications to be delivered on a particular thread that is determined by you instead of the notification center. For example, if an object running in a background thread is listening for notifications from the user interface, such as a window closing, you would like to receive the notifications in the background thread instead of the main thread. In these cases, you must capture the notifications as they are delivered on the default thread and redirect them to the appropriate thread.
意思很簡單鞠眉,NSNotificationCenter消息的接受線程是基于發(fā)送消息的線程的。也就是同步的择诈,因此械蹋,有時候,你發(fā)送的消息可能不在主線程羞芍,而大家都知道操作UI必須在主線程哗戈,不然會出現(xiàn)不響應(yīng)的情況。所以荷科,在你收到消息通知的時候唯咬,注意選擇你要執(zhí)行的線程。下面看個示例代碼
//接受消息通知的回調(diào)
- (void)test
{
if ([[NSThread currentThread] isMainThread]) {
NSLog(@"main");
} else {
NSLog(@"not main");
}
dispatch_async(dispatch_get_main_queue(), ^{
// do your UI
});
}
//發(fā)送消息的線程
- (void)sendNotification
{
dispatch_queue_t defaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(defaultQueue, ^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil];
});
}
總結(jié)
通知平常使用的知識點差不多就這么多步做。希望對大家有幫助副渴。最后,代碼一定要養(yǎng)成良好的習(xí)慣全度,該移除的還是要移除煮剧。