標籤:
// KVC: Key Value Coding, 常見作用:給模型屬性賦值
// KVO: Key Value Observing, 常用作用:監聽模型屬性值的改變
1 // 2 // ViewController.m 3 // 11-通知、KVO、代理 4 // 5 // Created by xiaomage on 15/6/6. 6 // Copyright (c) 2015年 xiaomage. All rights reserved. 7 // 8 9 #import "ViewController.h"10 #import "XMGPerson.h"11 12 @interface ViewController ()13 @property (nonatomic, strong) XMGPerson *p1;14 @property (nonatomic, strong) XMGPerson *p2;15 @property (nonatomic, strong) XMGPerson *p3;16 @end17 18 @implementation ViewController19 20 - (void)viewDidLoad {21 [super viewDidLoad];22 23 // self.p1 = [[XMGPerson alloc] init];24 // self.p1.name = @"p1";25 // 26 // self.p2 = [[XMGPerson alloc] init];27 // self.p2.name = @"p2";28 // 29 // self.p3 = [[XMGPerson alloc] init];30 // self.p3.name = @"p3";31 // 同一個通知TestNotification可以被多個對象person監聽32 // 當收到TestNotification通知就調用self.p1的test方法33 // [[NSNotificationCenter defaultCenter] addObserver:self.p1 selector:@selector(test) name:@"TestNotification" object:nil];34 // [[NSNotificationCenter defaultCenter] addObserver:self.p2 selector:@selector(test) name:@"TestNotification" object:nil];35 // [[NSNotificationCenter defaultCenter] addObserver:self.p3 selector:@selector(test) name:@"TestNotification" object:nil];36 // 多個對象可以發出同一個通知37 //對象@“123”發出TestNotification通知38 // [[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:@"123"];39 // [[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:@"345"];40 41 // KVC: Key Value Coding, 常見作用:給模型屬性賦值42 // KVO: Key Value Observing, 常用作用:監聽模型屬性值的改變43 44 45 self.p1 = [[XMGPerson alloc] init];46 self.p1.name = @"p1";47 //self.p1 監聽屬性 name的改變,NSKeyValueObservingOptionOld表示監聽方法中的NSDictional顯示舊值48 [self.p1 addObserver:self forKeyPath:@"name" options: NSKeyValueObservingOptionOld context:nil];49 50 self.p1.name = @"pppp1";51 }52 //所有的通知監聽 都要在dealloc銷毀時removeObserver53 - (void)dealloc54 {55 [self.p1 removeObserver:self forKeyPath:@"name"];56 }57 58 #pragma mark - KVO監聽方法59 /**60 * 當監聽到object的keyPath屬性發生了改變61 *這個方法是NSObject的類擴充方法,用來監聽對象屬性改變62 *keyPath屬性名稱如name63 *id 對象 如self.p164 *change 記錄改變前後的值65 */66 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context67 {68 NSLog(@"監聽到%@對象的%@屬性發生了改變, %@", object, keyPath, change);69 }70 71 @endView Code
ios通知-kvo