通知的使用方式:
1.注冊通知
2.發送通知
3.實現通知監聽的方法
4.移除通知
我對于通知的理解和困惑:好處就是解耦,給代碼分層,任何兩個類之間都可以使用通知來傳遞參數和實現一些業務邏輯,和代理,KVO有異曲同工之妙。個人認為通知會比代理寫代碼的時候簡單很多,但是有的時候會不知道在什么時機去移除通知。如果在控制器之間,明確知道生命周期的時候,使用通知是比較高效的,因為知道何時注冊通知,發送通知和移除通知。在單例對象中,最好不要注冊通知,因為單例在整個程序的運行過程中都是不會銷毀的,導致注冊的通知的也無法移除,會出現未知BUG。比如你注冊了多個同樣Name的通知,而且多次發送通知,會造成崩潰。
還有在鍵盤的通知使用中,要在viewWillAppear
中add通知,在viewWillDisappear
中remove 通知,因為viewWillAppear
和viewWillDisappear
這個方法會調用多次,當觸發側滑返回時會調用系統自帶的viewWillDisappear:方法,要是這時候用戶取消了側滑返回(即回側滑到一半又松手了), 這個時候如果移除了鍵盤通知就收不到鍵盤通知了,所以要在viewWillAppear
再次重新注冊鍵盤通知,才能防止用戶這種刁鉆操作影響了鍵盤的正常使用。
通知的類型:
有參和無參的區別就是在 發送通知的時候是否給通知中心傳遞參數,參數名是——userInfo
1.無參
[[NSNotificationCenter defaultCenter] postNotificationName:@"Notification_name" object:userProfile userInfo:沒有參數,這里就是空];
沒有參數的使用方法:
//發送通知
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"loadH5code" object:nil userInfo:nil]];
//注冊通知:
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loadH5code) name:@"loadH5code" object:nil];
//實現監聽方法
-(void)loadH5code{
// do something
}
2.有參
[[NSNotificationCenter defaultCenter] postNotificationName:@"Notification_name" object:userProfile userInfo:有參數,參數類型是NSDictionary];
所以命名參數的格式為
NSDictionary *dict = @{@"key":@"value"};
這是整個有參數的通知使用方法:
//發送通知
NSDictionary *dict = @{@"key":@"value"};
[[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"loadH5code" object:nil userInfo:dict]];
//注冊通知:
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loadH5code:) name:@"loadH5code" object:nil];
//實現監聽方法
-(void)loadH5code:(NSNotification *)notification
{
NSString *loadPathStr = notification.userInfo[@"key"];
if ([h5PathStr isEqualToString:@"value"]) {
// do something
}
}
最后就是移除通知了(切記要移除,不然有意想不到的欲罷不能欲仙欲死的bug)
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"loadH5code" object:self];