1. Student模型定义如下
- 在Student.h中
#import <Foundation/Foundation.h>
@interface Student : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSNumber *age;
@property (nonatomic, strong) NSNumber *height;
@property (nonatomic, strong) NSNumber *ID;
@end
- 在Student.m中
#import "Student.h"
@implementation Student
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
if ([key isEqualToString:@"id"]) {
self.ID = value;
}
}
@end
2. 给Student模型赋值
NSDictionary *studentInfo = @{@"name" : @"Kobe Bryant",
@"age" : @(18),
@"height" : @(190),
@"id" : @(20160101)};
Student *student = [[Student alloc] init];
[student setValuesForKeysWithDictionary:studentInfo];
3. KVC实现字典转模型存在的问题
- 必须保证,模型中的属性和字典中的key一一对应;
- 如果属性和key不能一一对应,就会报错
reason: '[<Student 0x10020cc00> setValue:forUndefinedKey:]
提示key找不到;
- 重写对象的
setValue:forUndefinedKey:
方法