OC学习 ----- 字典转模型

模型类 ,  即用来存放数据的类, 继承自NSObject. 

所谓模型,其实就是数据模型, 专门用来存放数据的对象,用它来表示会更加专业.

模型设置数据和取出数据都是通过它的属性, 属性名如果写错,编译器会马上报错,因此保证了数据的正确性.

使用模型访问属性时, 编译器会提供一系列的提示,提高编码效率.


 字典转模型应该提供一个可以传入字典参数的构造方法.  一般提供如下两个方法(一个对象方法和一个类方法) 为了与苹果公司原代码保持一致性,方法名称尽量模仿苹果公司规范来书写

<span style="font-size:14px;">-(instancetype)initWithDict:(NSDictionary *)dict;
+(instancetype)XXXWithDict:(NSDictionary *)dict;
</span>

 instancetype:在类型表示上,id一样,可以表示任何数据类型;

    instancetype只能用在返回值类型上,不能像id一样用在参数类型上;

    instancetypeid多一个好处:编译器会检测instancetype的真实类型.

根据数据字典的键值创建对应的数据模型. 在.h文件中声明模型属性及方法 .如下

<span style="font-size:14px;">#import <Foundation/Foundation.h>

@interface App : NSObject
/**
 *  名称
 */
@property (nonatomic, copy) NSString *name;
/**
 *  图标
 */
@property (nonatomic, copy) NSString *icon;
/**
 *  标题
 */
@property (nonatomic, weak) NSString *title;
/**
 *  答案
 */
@property (nonatomic, copy) NSString *answer;
 
/**
 *  通过字典来初始化模型对象
 *
 *  @param dict 字典对象
 *
 *  @return 已经初始化完毕的模型对象
 */
- (instancetype)initWithDict:(NSDictionary *)dict;
 
+ (instancetype)<strong>app</strong>WithDict:(NSDictionary *)dict;
@end</span>
字典转模型实现方法如下:

<span style="font-size:14px;">#import "App.h"
 
@implementation App
- (instancetype)initWithDict:(NSDictionary *)dict
{
    if (self = [super init]) {
      [self setValuesForKeysWithDictionary:dict];        // KVC方法
//  等效于以下几句:
//     self.name = dict[@"name"];
//     self.icon = dict[@"icon"];
//     self.title = dict[@"title"];
//     self.answer = dict[@"answer"];
 
    }
    return self;
}
 
+ (instancetype)appWithDict:(NSDictionary *)dict
{
    return [[self alloc] initWithDict:dict];
}
@end</span>
但是KVC的使用是有条件的 ;

由于KVC会将字典所有的键值对(key-value)赋值给模型对应的属性.只有当

1>  字典的键值对 个数 跟模型的 属性个数 相等

2>  属性名 必须和字典的 键值对 一样

时才可以使用KVC.

<span style="font-size:14px;">/**
 *  字典转模型,模型再次存入数组中 重写数组的set方法
 */
-(NSArray *)questions
{
    if (_questions ==nil) 
    {
        //加载plist,将plist中存储的字典数据放在数组dictArray中
        NSArray *dictArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"<span style="color:#FF0000;">questions.plist</span>" ofType:<span style="color:#FF0000;">nil</span>]];
         
        NSMutableArray *questionArray = [NSMutableArray array];
        //用自定义的JNQuestion模型question来接收 数组 dictArray 中的元素;
        for (NSDictionary * dict in dictArray)
        {
<span style="font-size: 12.5px;"></span><pre name="code" class="objc">
            Questions *question =[[LeeQuestions alloc]initWithDict:dict];</span>
// Questions *question = [LeeQuestions questionWithDict:dict]; [questionArray addObject:question];
} // 赋值 _questions = questionArray; } return _questions; }




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值