• 封装模型


    模型

    • 概念
      • 专门用来存放数据的对象
    • 特点
      • 一般直接继承自NSObject
      • 在.h文件中声明一些用来存放数据的属性
    • 首先创建实体类,具备属性,可用点语法
    • 模型定义示例
    @interface Shop : NSObject
    /** 名字 */
    @property (nonatomic, strong) NSString *name;
    /** 图标 */
    @property (nonatomic, strong) NSString *icon;
    
    /** 通过一个字典来初始化模型对象 */
    - (instancetype)initWithDict:(NSDictionary *)dict;
    
    /** 通过一个字典来创建模型对象 */
    + (instancetype)shopWithDict:(NSDictionary *)dict;
    @end
    
    • 字典转模型示例 ```objc
    • (instancetype)initWithDict:(NSDictionary *)dict { if (self = [super init]) {

        self.name = dict[@"name"];
        self.icon = dict[@"icon"];
      

      } return self; }

    • (instancetype)shopWithDict:(NSDictionary *)dict { // 这里要用self return [[self alloc] initWithDict:dict]; } ```

      字典转模型(懒加载)

    // 懒加载
    // 1.第一次用到时再去加载
    // 2.只会加载一次
    - (NSMutableArray *)shops
    {
        if (_shops == nil) {
            // 创建"模型数组"
            _shops = [NSMutableArray array];
    
            // 获得plist文件的全路径
            NSString *file = [[NSBundle mainBundle] pathForResource:@"shops.plist" ofType:nil];
    
            // 从plist文件中加载一个数组对象(这个数组中存放的都是NSDictionary对象)
            NSArray *dictArray = [NSArray arrayWithContentsOfFile:file];
    
            // 将 “字典数组” 转换为 “模型数据”
            for (NSDictionary *dict in dictArray) { // 遍历每一个字典
                // 将 “字典” 转换为 “模型”
                Shop *shop = [[Shop alloc] init];
                shop.name = dict[@"name"];
                shop.icon = dict[@"icon"];
    
                // 将 “模型” 添加到 “模型数组中”
                [_shops addObject:shop];
            }
        }
        return _shops;
    }
    

    注释

    // 单行注释
    /* */ 多行注释
    /** */ 文档注释
    #prama mark 跳转注释
  • 相关阅读:
    Web 日志分析过程
    nginx系列之九:lua服务
    Linux网络编程之IO模型
    从URL输入到页面展现到底发生什么
    CentOS 日常运维十大技能
    以MySQL为例,详解数据库索引原理(1)
    Elasticsearch的特点以及应用场景
    Ubuntu1804编译安装LNMP
    golang 高级
    Centos7 安装 Redis
  • 原文地址:https://www.cnblogs.com/ShaoYinling/p/4603310.html
Copyright © 2020-2023  润新知