封装模型

模型

  • 概念
    • 专门用来存放数据的对象
  • 特点
    • 一般直接继承自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 跳转注释

转载于:https://www.cnblogs.com/ShaoYinling/p/4603310.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值