封装模型

模型

  • 概念
    • 专门用来存放数据的对象
  • 特点
    • 一般直接继承自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 跳转注释
posted @ 2015-06-26 21:59  ShaoYL  阅读(536)  评论(0编辑  收藏  举报