对plist构建数据模型,完成封装实现数据分离

来源:互联网 发布:淘宝指数查询 编辑:程序博客网 时间:2024/06/02 06:12

pList是我们常用的数据格式,首先来看我们的pList文件:是一个数组,里面存放字典,字典分为两项,name对应名字,icon对应图片名字,我们还有一组以此命名的图片。



对此,为了封装数据,我们建一个类,取名AppInfo.

AppInfo.h文件:


#import <Foundation/Foundation.h>#import <UIKit/UIKit.h>@interface AppInfo : NSObject@property (nonatomic,copy) NSString *name;@property (nonatomic,copy) NSString *icon;@property (nonatomic,strong,readonly) UIImage *image;/** 使用字典实例化 */+ (instancetype)initWithDictionary:(NSDictionary *)dict;/** 类方法快速实例化 */+ (instancetype)appInfoWithDictionary:(NSDictionary *)dict;+ (NSArray *)appList;@end


 AppInfo.m文件:

#import "AppInfo.h"@implementation AppInfo@synthesize image = _image;- (UIImage *)image{    if(_image == nil ){        _image = [UIImage imageNamed:self.icon];    }    return _image;}- (instancetype)initWithDictionary:(NSDictionary *)dict{    self = [super init];    if (self) {        //KVC        [self setValuesForKeysWithDictionary:dict];            }    return self;}+ (instancetype)appInfoWithDictionary:(NSDictionary *)dict{    return [[self alloc]initWithDictionary:dict];}+(NSArray *)appList{    NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"app.plist" ofType:nil]];        NSMutableArray *arrayM = [NSMutableArray array];    for (NSDictionary *dict in array) {        AppInfo *appInfo = [AppInfo appInfoWithDictionary:dict];        [arrayM addObject:appInfo];    }        return arrayM;}@end

这样,在需要取数据的时候,只需调用 :
NSArray *array = [AppInfo appList];
就能得到一个AppInfo数组,其中Image,name都已经封装到了AppInfo中,直接取值即可。



0 0
原创粉丝点击