iOS 字典转模型 KVC实现

1. Student模型定义如下

  1. 在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

  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: '[<Student 0x10020cc00> setValue:forUndefinedKey:]提示key找不到;
  • 重写对象的setValue:forUndefinedKey:方法
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容