feat: 初始化

This commit is contained in:
杭城小刘
2018-09-11 10:11:39 +08:00
committed by 杭城小刘
commit 8e5d2c9e7f
264 changed files with 12082 additions and 0 deletions

57
第一部分 iOS/1.48.md Normal file
View File

@@ -0,0 +1,57 @@
### 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;
}
}
```