在使用许多数据的时候一般用模型来存储数据的类。
开发时当我们从文件中取出数据到字典后,应该将数据从字典取出装到模型中,将面向字段开发转为面向模型开发。
模型对象的参数选择:
copy:NSString
Strong:一般对象
weak:UI控件
assign:基本数据类型。
PS
:注意模型方法的规范。
比如 需要一个需要一个initWithXXX的对象方法,以及一个以对象吗开头的 xxxwithXXX为名的类方法。
并且在类方法中简单地直接调用对象方法就好了。
举例:
头文件:
#import <Foundation/Foundation.h>
@interface MyApp : NSObject
@property(nonatomic, copy)NSString *icon;
@property(nonatomic, copy)NSString *name;
- (instancetype)initWithDict:(NSDictionary *)dict;
+ (instancetype)myAppWithDict:(NSDictionary *)dict;
@end
实现文件:
#import "MyApp.h"
@implementation MyApp
- (instancetype)initWithDict:(NSDictionary *)dict
{
if (self == [super init]) {
self.icon= dict[@"icon"];
self.name= dict[@"name"];
}
return self;
}
+ (instancetype)myAppWithDict:(NSDictionary *)dict
{
return [[self alloc]initWithDict:dict];
}
@end
plist文件中数据转为数据模型一般过程:
- (NSArray *)apps
{
if (_apps == nil) {
//1、获取plist文件路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"app.plist" ofType:nil];
//2、从路径中获取plist中的字典
NSArray *array = [NSArray arrayWithContentsOfFile:path];
//3、创建接受数据模型的可变数组
NSMutableArray *apparray = [NSMutableArray array];
//4、依次取出字典,循环存储到数据模型中
for (NSDictionary*dataDictionary in array) {
//新建单条数据模型
MyApp *app = [MyApp myAppWithDict:dataDictionary];
//添加到可变数组中
[apparray addObject:app];
}
//5、将数据模型数组赋值到成员变量中
_apps = apparray;
}
return _apps;
}