首页 > 代码库 > Objective-C 观察者模式--KVO和NSNotificationCenter的使用

Objective-C 观察者模式--KVO和NSNotificationCenter的使用

Objective-C中的KVO和NSNotificationCenter的原理是观察模式的很好实现, 下面用代码分别演示下用法

 

KVO的用法

 1 - (void)viewDidLoad {
 2     [super viewDidLoad];
 3     // Do any additional setup after loading the view, typically from a nib.
 4 
 5     self.model = [Model new];
 6     
 7     //添加KVO
 8     [self.model addObserver:self
 9                  forKeyPath:@"name"
10                     options:NSKeyValueObservingOptionNew
11                     context:nil];
12     
13     //发送信息, 通过修改属性
14     self.model.name = @"v1.0";
15      
16 }
17 
18 #pragma mark - KVO方法
19 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
20     NSLog(@"%@", change);
21 }
22 
23 - (void)dealloc {
24 
25     //移除KVO
26     [self.model removeObserver:self
27                     forKeyPath:@"name"];
28 }

 

 

NSNotificationCenter的用法

 1 - (void)viewDidLoad {
 2     [super viewDidLoad];
 3     // Do any additional setup after loading the view, typically from a nib.
 4     
 5     //添加
 6     [[NSNotificationCenter defaultCenter] addObserver:self
 7                                              selector:@selector(notificationCenterEvent:)
 8                                                  name:@"SCIENCE"
 9                                                object:nil];
10     
11     //发送信息
12     [[NSNotificationCenter defaultCenter] postNotificationName:@"SCIENCE"
13                                                         object:@"v1.0"];
14     
15 }
16 
17 #pragma mark - 通知中心方法
18 - (void)notificationCenterEvent:(id)sender {
19     NSLog(@"%@", sender);
20 }
21 
22 - (void)dealloc {
23     //移除通知中心
24     [[NSNotificationCenter defaultCenter] removeObserver:self
25                                               forKeyPath:@"SCIENCE"];
26 
27 }

 

Objective-C 观察者模式--KVO和NSNotificationCenter的使用