KVO與通知都可實現觀察者模式。
一、通知簡介
NSNotificationCenter是一個消息通知機制,類似廣播。觀察者只需要向消息中心注冊消息,當有地方發出這個消息的時候,通知中心會發送給注冊這個消息的對象。消息發送者和消息接受者兩者可以互相一無所知,完全解耦。
觀察者向消息中心注冊以后,在不需要接受消息時需要向消息中心注銷,屬于典型的觀察者模式。
消息通知中重要的兩個類:
(1) NSNotificationCenter: 實現NSNotificationCenter的原理是一個觀察者模式,獲得NSNotificationCenter的方法只有一種,那就是[NSNotificationCenter defaultCenter] ,通過調用靜態方法defaultCenter就可以獲取這個通知中心的對象了。NSNotificationCenter是一個單例模式,而這個通知中心的對象會一直存在于一個應用的生命周期。
(2) NSNotification: 這是消息攜帶的載體,通過它,可以把消息內容傳遞給觀察者。
二、通知的使用
1、在當前控制器發送通知接收通知
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//1.注冊通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(firstNotificationFunc:) name:@"First" object:nil];
}
//2.通知回調方法
- (void)firstNotificationFunc:(NSNotification *)notification{
NSString *name = [notification name];
NSLog(@"打印%@",name);
}
//3.銷毀
- (void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
//4.發送通知
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[[NSNotificationCenter defaultCenter] postNotificationName:@"First" object:self];
}
@end
注意:只有注冊通知之后才可以接收發送的通知。
通知可傳遞參數,userInfo、object。
2、在push的下一界面發送通知,在上一控制器接收通知
//第一個控制器
#import "ViewController.h"
#import "NextViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"第一個控制器";
//1.注冊通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(firstNotificationFunc:) name:@"First" object:nil];
}
//2.通知回調方法
- (void)firstNotificationFunc:(NSNotification *)notification{
NSString *name = [notification name];
NSLog(@"打印%@%@",self.title,name);
}
//3.銷毀
- (void)dealloc{
[[NSNotificationCenter defaultCenter] removeObserver:self];
NSLog(@"銷毀");
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//跳轉
NextViewController *vc = [[NextViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
}
@end
**********************************************************
//第二個控制器
#import "NextViewController.h"
@interface NextViewController ()
@end
@implementation NextViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.title = @"第二個控制器";
self.view.backgroundColor = [UIColor whiteColor];
}
//發送通知
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[[NSNotificationCenter defaultCenter] postNotificationName:@"First" object:nil];
}
@end
//也可以根據通知名移除注冊的通知
- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;
三、通知的優缺點
優點:
- 不需要編寫多少代碼,實現比較簡單。
- 對于一個發出的通知,多個對象能夠做出反應,即一對多的消息通知機制。
- 可以傳遞參數,userInfo, object。
缺點:
- 在編譯器不會檢查通知是否能夠被觀察者正確的處理;
- 注冊的觀察者,一定要移除。
- 只有注冊了通知,才能接收通知消息。注冊通知對象要在發送通知的前面才可接收到通知。
- 通知發出后,controller不能從觀察者獲得任何的反饋信息。