標籤:load after new 修改 通知 model move key 修改屬性
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:NSKeyValueObservingOptionNew11 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 //移除KVO26 [self.model removeObserver:self27 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:self25 forKeyPath:@"SCIENCE"];26 27 }
Objective-C 觀察者模式--KVO和NSNotificationCenter的使用