iOS-字典转模型 和 kvc

模型.h文件

#import <Foundation/Foundation.h>

@interface LFQuestion : NSObject

@property (nonatomic, copy) NSString *answer;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *icon;
@property (nonatomic, strong) NSArray *options;

@property (nonatomic, strong) UIImage *image;

/** 用字典实例化对象的成员方法 */
- (instancetype)initWithDict:(NSDictionary *)dict;
/** 用字典实例化对象的类方法,又称工厂方法 */
+ (instancetype)questionWithDict:(NSDictionary *)dict;

/** 从plist加载对象数组 */
+ (NSArray *)questions;

@end

模型.m文件

#import "LFQuestion.h"

@implementation LFQuestion

+ (instancetype)questionWithDict:(NSDictionary *)dict
{
    return [[self alloc] initWithDict:dict];
}

- (instancetype)initWithDict:(NSDictionary *)dict
{
    self = [super init];
    if (self) {
        self.answer = dict[@"answer"];
        self.icon = dict[@"icon"];
        self.title = dict[@"title"];
        self.options = dict[@"options"];
        
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}


+ (NSArray *)questions
{
    NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"questions.plist" ofType:nil]];
    
    NSMutableArray *arrayM = [NSMutableArray array];
    
    for (NSDictionary *dict in array) {
        [arrayM addObject:[LFQuestion questionWithDict:dict]];
    }
    
    return arrayM;
}
@end

二、 (KVC)的使用

(1)在模型内部的数据处理部分,可以使用键值编码来进行处理

- (instancetype)initWithDict:(NSDictionary *)dict
{
    self = [super init];
    if (self) {
//        self.answer = dict[@"answer"];
//        self.icon = dict[@"icon"];
//        self.title = dict[@"title"];
//        self.options = dict[@"options"];
        
        // KVC (key value coding)键值编码
        // cocoa 的大招,允许间接修改对象的属性值
        // 第一个参数是字典的数值
        // 第二个参数是类的属性
        [self setValue:dict[@"answer"] forKeyPath:@"answer"];
        [self setValue:dict[@"icon"] forKeyPath:@"icon"];
        [self setValue:dict[@"title"] forKeyPath:@"title"];
        [self setValue:dict[@"options"] forKeyPath:@"options"];
    }
    return self;
}

(2)setValuesForKeys的使用

上述数据操作细节,可以直接通过setValuesForKeys方法来完成。

- (instancetype)initWithDict:(NSDictionary *)dict
{
    self = [super init];
    if (self) {
        // 使用setValuesForKeys要求类的属性必须在字典中存在,可以比字典中的键值多,但是不能少。
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值