iOS 字典转模型 KVC实现

2017-07-25  本文已影响102人  Jixin

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实现字典转模型存在的问题

上一篇 下一篇

猜你喜欢

热点阅读