KVC與KVO的區別
一.鍵值編碼–KVC
KVC的操作方法由NSKeyValueCoding協議提供的,而NSObjct就實現了這個協議,也就是說objc中幾乎所有的對象都支持KVC操作的,常用的KVC操作方法如下:
方法1:
//設置
//通過屬性名(作爲Key)爲其賦值
- (void)setValue:(nullable id)value forKey:(NSString *)key;
//實例:通過姓名的作爲key給self對象的name和age屬性賦值
[self setValue:@"羅升強" forKey:@"name"];
[self setValue:@(22) forKey:@"age"];
方法2:
//複合路徑賦值
- (id)valueForKeyPath:(NSString *)keyPath
//實例:self對象中擁有XJK類的屬性money
[self setValue:@(10000) forKeyPath:@"money.number"];
方法3:字典轉模型的時候使用的
- (void)setValuesForKeysWithDictionary:(NSDictionary<NSString *,id> *)keyedValues
以上的KVC的原理:
LSQStudent *stu = [[self alloc] init];
// [obj setValuesForKeysWithDictionary:dict];
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull value, BOOL * _Nonnull stop) {
// NSLog(@"%@--%@",key,value);
[stu setValue:value forKeyPath:key];
}];
方法4:通過KVC讀取
- (nullable id)valueForKey:(NSString *)key;
- (nullable id)valueForKeyPath:(NSString *)keyPath;
//實例:
- (NSString *)description
{
//通過key讀取value值
return [NSString stringWithFormat:@"%@,%@",[self valueForKey:@"name"],[self valueForKey:@"age"] ];
}
方法5:(很少使用,瞭解就可以了)
dictionaryWithValuesForKeys: 輸入一組key,返回這組key的所有值;
- (NSDictionary<NSString *, id> *)dictionaryWithValuesForKeys:(NSArray<NSString *> *)keys;
注意:KVC的缺陷
點擊一下鏈接進行跳轉查看:KVC缺陷
二.鍵值監聽–KVO
- 1.KVO,即:Key-Value Observing,它提供一種機制,當指定的對象的屬性被修改後,則對象就會接受到通知。簡單的說就是每次指定的被觀察的對象的屬性被修改後,KVO就會自動通知相應的觀察者了。
- 2.使用方法(具體查看本作者KVO的使用博客)
系統框架已經支持KVO,所以程序員在使用的時候非常簡單。
- 註冊,指定被觀察者的屬性,
- 實現回調方法
- 移除監聽