iOS之KVO Tips
key
或keypath
匹配addObserver: forKeyPath: options: context:
的“keypath”和setValue: forKey
的“key”或setValue: forKeyPath:
的“keyPath”或setter方法对应的属性名保持一致,observeValueForKeyPath: ofObject: change: context:
方法才会被触发。1
2
3
4
5
6
7
8
9
10
11//self.student.name
[self.student addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];
[self.student setName:@"baylee"];//student有"name"属性或成员变量
[self.student setValue:@"baylee" forKey:@"name"];
//self.student有teacher属性,teacher有个className属性
[self.student addObserver:self forKeyPath:@"teacher.className" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:NULL];
self.student.teacher.className = @"english";
[self.student setValue:@"english" forKeyPath:@"teacher.className"];