zoukankan      html  css  js  c++  java
  • 封装模型

    模型

    • 概念
      • 专门用来存放数据的对象
    • 特点
      • 一般直接继承自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 跳转注释
  • 相关阅读:
    Oracle学习(四)--sql及sql分类讲解
    Oracle学习(三)--数据类型及常用sql语句
    Oracle学习(二)--启动与关闭
    Tomcat学习笔记--启动成功访问报404错误
    有关Transaction not successfully started问题解决办法
    百度富文本编辑器UEditor1.3上传图片附件等
    hibernate+junit测试实体类生成数据库表
    js登录与注册验证
    SVN安装配置与使用
    [LeetCode] #38 Combination Sum
  • 原文地址:https://www.cnblogs.com/ShaoYinling/p/4603310.html
Copyright © 2011-2022 走看看