数据模型的构建及懒加载数据

1、数据模型的构建

#import <Foundation/Foundation.h>

@interface AppModel : NSObject

@property (nonatomic, strong) NSString *icon;
@property (nonatomic, strong) NSString *name;

- (instancetype)initWithDict:(NSDictionary *)dict;

+ (instancetype)appModelWithDict:(NSDictionary *)dict;

@end
#import "AppModel.h"

@implementation AppModel
- (instancetype)initWithDict:(NSDictionary *)dict {
  if (self = [super init]) {
    
    [self setValuesForKeysWithDictionary:dict];
  }
  
  return self;
}

+ (instancetype)appModelWithDict:(NSDictionary *)dict {
  return [[self alloc] initWithDict:dict];
}


@end

 

2、懒加载数据

@interface ViewController ()

@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation ViewController
- (NSMutableArray *)dataArray { if (nil == _dataArray) { _dataArray = [NSMutableArray array]; //从plist中读取数据 NSString *path = [[NSBundle mainBundle] pathForResource:@"app.plist" ofType:nil]; NSArray *array = [NSArray arrayWithContentsOfFile:path]; //字典转模型 for (NSDictionary *dict in array) { AppModel *model = [AppModel appModelWithDict:dict]; [_dataArray addObject:model]; } } return _dataArray; } @end

PS:因为重写了getter方法,故调用时必须调用self.dataArray[]

 

posted on 2016-02-13 21:28  微末凡尘12138  阅读(253)  评论(0编辑  收藏  举报

导航