目標:監聽NSMutableArray對象中增加了什么
代碼如下:
- (void)viewDidLoad{ [super viewDidLoad]; self.dataArray = [NSMutableArray arrayWithObject:@"1"]; [self addObserver:self forKeyPath:@"dataArray" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL]; }
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ NSLog(@"%@", keyPath); NSLog(@"%@", object); NSLog(@"%@", change);}
- (IBAction)add:(id)sender{ NSArray *addData = [NSArray arrayWithObjects:@"11", @"12", @"13", nil]; [self.dataArray addObjectsFromArray:addData]; self.dataArray = [NSMutableArray arrayWithObject:@"2"];}
輸入日志:
2013-01-15 16:05:10.120 KVOTest[2199:907] dataArray2013-01-15 16:05:10.121 KVOTest[2199:907] <ZZTViewController: 0x20846590>2013-01-15 16:05:10.123 KVOTest[2199:907] { kind = 1; new = ( 2 ); old = ( 1, 11, 12, 13 );}
經過測試得如下結論:kvo監聽的是對象指針的變動,NSString、int、float等對象的變動(abc = @"123"、abc = 12、abc = 12.2)皆為指針的變動,所以通過此方式來捕捉array的變化是不可行的
但,我們可以通過此方式來做控件屬性的變動。如下:
- (void)viewDidLoad{ [super viewDidLoad]; self.personObject = [PersonObject personObjectWithBankInstance:[BankObject bankObjectWithAccountBalance:10]]; [self.personObject addObserver:self forKeyPath:@"bankInstance.accountBalance" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL]; // 此處注意是監聽personObject對象下的bankInstance的accountBalance變化}
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{ NSLog(@"%@", keyPath); NSLog(@"%@", object); NSLog(@"%@", change);}
- (IBAction)add:(id)sender{ [self.personObject.bankInstance setAccountBalance:2111];}
輸出日志:
2013-01-15 16:05:10.111 KVOTest[2199:907] bankInstance.accountBalance2013-01-15 16:05:10.116 KVOTest[2199:907] <PersonObject: 0x20856180>2013-01-15 16:05:10.118 KVOTest[2199:907] { kind = 1; new = 2111; old = 10;}
如有問題,請留言共同探討。
新聞熱點
疑難解答