KVO (Key-Value-Observer, 键值观察)
KVO (Key-Value-Observer, 键值观察)
valueForKey 和 valueForKeyPath区别
valueForKeyPath是valueForKey的升级, valueForKey都能用valueForKeyPath, valueForKey只能一层
KVC计算数组和
NSArray *array = @[@"1", @"2", @"3", @"4", @"5"];
NSNumber *sum = [array valueForKeyPath:@"@sum.integerValue"];
NSLog(@"%@", sum);
KVC修改 UITextField的占位字符颜色
// 设置占位文字的颜色为红色
[self setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
KVO: Key-Value-Observer, 键值观察
1.添加观察者
第一个self代表被观察对象
第二个self代表观察者
KeyPath 实例变量路径
options 可选项, 可以添加多个, 中间用|分开
context 上下文, 可以用来传值
[self addObserver:self forKeyPath:@"name" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil];
//初始化可变数组
self.array = [@[] mutableCopy];
//添加观察者
[self addObserver:self forKeyPath:@"array" options:(NSKeyValueObservingOptionNew) context:nil];
2. 接收KVO的事件
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
NSLog(@"object = %@, keyPath = %@ change = %@", object, keyPath, change);
}
- (IBAction)kvo_fire:(id)sender {
self.name = @"568";
}
- (IBAction)array_KVO_fire:(id)sender {
// [self.array addObject:@"123"];
[[self mutableArrayValueForKey:@"array"] addObject:@"OK"];
}
- (void)dealloc
{
//3. 移除观察者
[self removeObserver:self forKeyPath:@"name"];
[self removeObserver:self forKeyPath:@"array"];
}
The one who wants to wear a crown must bear the weight!