mirror of
https://github.com/NohamR/knowledge-kit.git
synced 2026-05-26 13:41:32 +00:00
58 lines
1.5 KiB
Markdown
58 lines
1.5 KiB
Markdown
### KVC && KVO
|
||
|
||
### 字典快速赋值
|
||
|
||
KVC 可以将字典里面和 model 同名的 property 进行快速赋值 **setValuesForKeysWithDictionary**
|
||
|
||
```objective-c
|
||
//前提:model 中的各个 property 必须和 NSDictionary 中的属性一致
|
||
- (instancetype)initWithDic:(NSDictionary *)dic{
|
||
BannerModel *model = [BannerModel new];
|
||
[model setValuesForKeysWithDictionary:dic];
|
||
return model;
|
||
}
|
||
```
|
||
|
||
但是这里会有2种特殊情况。
|
||
|
||
情况一:在 model 里面有 property 但是在 NSDictionary 里面没有这个值
|
||
|
||
运行上面的代码,代码不崩溃,只不过在输出值的时候输出了 null
|
||
|
||
情况二:在 NSDictionary 中存在某个值,但是在 model 里面没有值
|
||
|
||
运行后编译成功,但是代码奔溃掉。原因是 KVC 。所以我们只需要实现这么一个方法。甚至不需要写函数体部分
|
||
|
||
```
|
||
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{
|
||
|
||
}
|
||
```
|
||
|
||
情况三:如果 Dictionary 和 Model 中的 property 不同名
|
||
|
||
我们照样可以利用 **setValue:forUndefinedKey:** 去处理
|
||
|
||
比如
|
||
|
||
```objective-c
|
||
//model
|
||
@property (nonatomic,copy)NSString *name;
|
||
@property (nonatomic,copy)NSString *sex;
|
||
@property (nonatomic,copy) NSString* age;
|
||
//NSDictionary
|
||
NSDictionary *dic = @{@"username":@"张三",@"sex":@"男",@"id":@"22"};
|
||
|
||
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
|
||
if([key isEqualToString:@"id"]){
|
||
self.age=value;
|
||
}
|
||
if([key isEqualToString:@"username"]){
|
||
self.name=value;
|
||
}
|
||
}
|
||
```
|
||
|
||
|
||
|