KVC key value coding 相当于OC的类对象 . 语法直接赋值
@interface People : NSObject
@property (nonatomic) int name;
@property (nonatomic) NSString *nameStr;
@end
People *p = [[People alloc]init];
[p setValue:@2 forKey:@"name"];
[p setValue:@"sdfsdf" forKey:@"nameStr"];
array = [NSMutableArray new];
[array addObject:p];
int a = [[p valueForKey:@"name"] intValue];
NSString *a2 = [p valueForKey:@"nameStr"];
KVO 监听值变化,当监听的key 的 value值变化时,会触发
observeValueForKeyPath
必须是全局变量或者用数组保存局部变量,否则会报错:An instance 0x60000002f940 of class People was deallocated while key value observers were still registered with it. Current observation info: <NSKeyValueObservationInfo 0x60000002ff00> (
<NSKeyValueObservance 0x60000005e3c0: Observer: 0x7fc3fad0c030, Key path: nameStr, Options: <New: NO, Old: NO, Prior: NO> Context: 0x103cdd298, Property: 0x60000005e450>
)'
static NSString * const KVO_NameStr_CHANGED = @"KVO_CONTEXT_ADDRESS_CHANGED";
[p addObserver:self forKeyPath:@"nameStr" options:0 context:(__bridge void * _Nullable)(KVO_NameStr_CHANGED)];
-(void)dealloc
{
People *p = [array objectAtIndex:0];
[p removeObserver:self forKeyPath:KVO_NameStr_CHANGED];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
if (context == (__bridge void * _Nullable)(KVO_NameStr_CHANGED))
{
NSLog(@"%@",[object valueForKey:@"nameStr"]);
}
}
-(void)buttonClickToChangKVO
{
// p.nameStr = @"200";
People *p = [array objectAtIndex:0];
p.nameStr = @"200";
}