Files
knowledge-kit/第一部分 iOS/1.48.md
2020-02-25 17:35:10 +08:00

58 lines
1.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
### 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;
}
}
```