iOS 字典转模型 KVC实现

1. Student模型定义如下

  1. 在Student.h中
#import 

@interface Student : NSObject

@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSNumber *age;
@property (nonatomic, strong) NSNumber *height;
@property (nonatomic, strong) NSNumber *ID;

@end

  1. 在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: '[ setValue:forUndefinedKey:]提示key找不到;
  • 重写对象的setValue:forUndefinedKey:方法

你可能感兴趣的:(iOS 字典转模型 KVC实现)