• 字典转模型对象


    这里主要是说NSDictionary转模型对象的核心代码,和需要注意点。

    /***
     *  从处理plist中的数据 并返回模型对象的数组
     *
     *  @return  NSArray *apps;
     */
    -(NSArray *) apps{
        if (_apps==nil) {
            // 过去plist的全路径
            NSString *path=[[NSBundle mainBundle]pathForResource:@"app.plist" ofType:nil];
            //加载数组
            NSArray *dicArray=[NSArray arrayWithContentsOfFile:path];
            //将dicArray里面的所有字典转成模型对象,放到新的数组中。
            NSMutableArray *appArray=[NSMutableArray  array];
            for (NSDictionary *dict in dicArray) {
                //创建模型对象
           //initWithDict 自定义对象方法
                MyApp *app=[[MyApp alloc] initWithDict:dict];
                 
                /***[NSString stringWithFormat:<#(NSString *), ...#>];
                [[NSString alloc] initWithFormat:<#(NSString *), ...#>];
                
                [NSArray arrayWithContentsOfFile:<#(NSString *)#>]
                [[NSArray alloc] initWithContentsOfFile:<#(NSString *)#>;**/
                 /**通过这里 我们需要提取一个appWith
                MyApp *app=[MyApp appWithDict:dict];
                //添加到对象到数组中
                [appArray addObject:app];
            }
            //赋值
            _apps=dicArray;
            
        }
        return _apps;
    }





    #import <Foundation/Foundation.h> /** * copy :NSString strong :一般对象 weak:UI控件 assign :基本数据类型 */ @interface MyApp : NSObject /** * 图标 */ @property (nonatomic,copy) NSString *icon; /** * 名称 */ @property(nonatomic,copy) NSString *name; /** * 通过字典来初始化模型对象 * * @param dic 字典对象 * * @return 已经初始化完毕的模型对象 */ /* instancetype的作用,就是使那些非关联返回类型的方法返回所在类的类型! 好处能够确定对象的类型,能够帮助编译器更好的为我们定位代码书写问题
    instanchetype和id的对比
    1、相同点
    都可以作为方法的返回类型
    
    2、不同点
    ①instancetype可以返回和方法所在类相同类型的对象,id只能返回未知类型的对象;
    
    ②instancetype只能作为返回值,不能像id那样作为参数,比如下面的写法:
    */
    -(instancetype)initWithDict:(NSDictionary *)dict;
    
    +(instancetype) appWithDict:(NSDictionary *)dict;
    @end
    复制代码
  • 相关阅读:
    由 基本数据型态转换成 String/ 由 String 转换成 数字的基本数据型态
    屏幕适配(UGUI)非UI
    转载 Unity Text 插入超链接
    File类的使用
    抽奖
    竖倾斜ScrollView
    本地资源_Asset
    小型自动朝向转盘
    简易C# socket
    Lua class
  • 原文地址:https://www.cnblogs.com/it38/p/4985180.html
Copyright © 2020-2023  润新知