KVC 详解: http://www.2cto.com/kf/201507/415647.html
ActivityModel *activityModel = [[ActivityModel alloc] init];
[activityModel setValuesForKeysWithDictionary:temp]; //KVC赋值[self.dataArray addObject:activityModel];
需要注意的是 KVC赋值的时候 所创建model模型里面的属性必须和KVC字典里的key值相对应
如果model里面的属性可以是不属于比KVC的字典的key
但是kvc里面的key 如果在model里面没有对应的属性,model必须重写方法
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{}
不写的话 会报错
setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key image_hlarge.
为了实现对嵌套json的处理,(后者自定义key的赋值方法)我们需要重写-(void)setValue:(id)value forKey:(NSString *)key方法
例子:见最后
======================================================================
KVO
只要对被观察者被重新赋值 就会走观察方法 不管所赋的值是否变化
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"%@",keyPath);
NSLog(@"%@",object);
NSLog(@"%@",change);
NSLog(@"%@",context);
//1.取值
id new = [object valueForKeyPath:keyPath];
NSLog(@"%@",new);
//2.取值
id new1 = [change objectForKey:NSKeyValueChangeNewKey];
NSLog(@"new1---%@",new1);
}
// KVC 赋值例子
@interface DetailModel :NSObject
@property (nonatomic,copy)NSString *name;
@property (nonatomic,copy)NSString *objectId;
@property (nonatomic,copy)NSString *userId;
@property (nonatomic, copy) NSString *createdAt;
@property (nonatomic,copy)NSString *headerImage;
@property (nonatomic, assign) NSNumber *age;
@implementation DetailModel
-(void)setValue:(id)value forUndefinedKey:(NSString *)key {
}
-(void)setValue:(id)value forKey:(NSString *)key {
if ([keyisEqual:@"headerImage"]) {
// 自定义 headerImage的赋值 因为headerImage 在返回中是个字典,而有用的只要url
_headerImage = [valueobjectForKey:@"url"];
} else {
[supersetValue:valueforKey:key];
}
}
-(NSString*)description;
JSON:
{
age = 20;
createdAt = "2015-09-17T02:40:45.219Z";
headerImage = {
"__type" = File;
bucket = sNkArza7;
createdAt = "2015-09-17T10:48:35.621Z";
key = "KsjzUhNAdymW0FNjcxEgR3D.png";
metaData = {
"_checksum" = 121f6ec8713bfd3a7c6143fb2a0f5d4d;
owner = 55fa1da860b232fc2abc51d7;
size = 2369719;
};
"mime_type" = "image/png";
name = "avatar.png";
objectId = 55fa9a83ddb2e44a4844974c;
updatedAt = "2015-09-17T10:48:35.621Z";
url = "http://ac-sNkArza7.clouddn.com/KsjzUhNAdymW0FNjcxEgR3D.png";
};
name = "\U660e\U661f";
objectId = 55fa282d60b25f2389575a49;
updatedAt = "2015-09-17T10:48:38.259Z";
userId = 55fa1da860b232fc2abc51d7;
}
DetailModel *model = [[DetailModelalloc]init];
[model setValuesForKeysWithDictionary:responseObject];
NSLog(@"%@", model);
userId: 55fa1da860b232fc2abc51d7,
name: 明星,
objectId: 55fa282d60b25f2389575a49,
age: 20,
creat: 2015-09-17T02:40:45.219Z,
_headerImage: http://ac-sNkArza7.clouddn.com/KsjzUhNAdymW0FNjcxEgR3D.png