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

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中,直接取值即可。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值