zoukankan      html  css  js  c++  java
  • setValuesForKeysWithDictionary:的用途

       setValuesForKeysWithDictionary :今天发现这个高大上的功能,让我心奋不已,以后妈妈再也不用担心模型属性多了,再也不用担心将字典中的值赋值到模型中的麻烦操作了。

        模型的.h文件

    #import <Foundation/Foundation.h>
    
    @interface appModel : NSObject
    @property(nonatomic,copy)NSString * name;
    @property(nonatomic,copy)NSString * icon;
    -  (instancetype)initWithApp:(NSDictionary *)dict;
    + (instancetype)appWithDict:(NSDictionary *)dict;
    @end

        模型的.m文件

    @implementation appModel
    - (instancetype)initWithApp:(NSDictionary *)dict
    {
        //构造方法中必须有self = [super init]的判断
        if (self =[super init]) {
            //将字典中的数据取出,赋值给模型
            self.name = dict[@"name"];
            self.icon = dict[@"icon"];
        }
        
        return  self;
    }
    /**
     *  也可以通过类方法进行取值
     *
     *  @param dict <#dict description#>
     *
     *  @return <#return value description#>
     */
    + (instancetype)appWithDict:(NSDictionary *)dict
    {
        return  [[appModel alloc] initWithApp:dict];
    }
    @end

         看到我们在构造方法中做的事情了吧,目前只有两个属性需要赋值,试想如果我们需要给一千个属性进行赋值,那么我们的工作是多么枯燥无味,而且为了一个这么没有技术含量的事情话费这么多的时间是没有必要的。所以xcode提供了setValuesForKeysWithDictionary:这方法进行赋值,直接减少了我们的工作量。代码如下:

    @implementation herosModel
    /**
     *  类方法
     *  辅助功能 同构造方法功能一致
     */
    +(instancetype)herosModelWithDict:(NSDictionary*) dict
    {
        return  [[herosModel alloc]initWithDict:dict];
    }
    /**
     *  构造方法
     */
    -(instancetype)initWithDict:(NSDictionary*)dict
    {
        //需要先判断一下父类方法
        if (self=[super init]) {
            //通过映射的方法,将字典中的每一个元素根heros中的属性进行逐个映射;
            [self setValuesForKeysWithDictionary:dict];
        }
        return  self;
    }
    @end

        setValuesForKeysWithDictionary: ,非常好用,不需要你来一一的给对象赋值而直接从字典初始化即可,但用的不好会经常崩溃!这个希望大家在使用过程中多注意。

  • 相关阅读:
    (原创)常用加密解密
    Winforms和资源(Resources/resx)
    delphi中的第三方控件如何安装 (转)
    IT博客
    访问FTP (转)
    设置radasm,使其支持8086 16位asm(转)
    EditPlus注册码(转)
    windows资源管理器已停止工作 (转)
    当发生异常时,怎样能不让‘delphi的异常提示框出现’而出现自己的‘异常提示框’?
    清除复制网页带过来的背景颜色 (转)
  • 原文地址:https://www.cnblogs.com/pengpengzhang/p/4555003.html
Copyright © 2011-2022 走看看