IOS加载plist文件、懒加载与数据模型相关

2019-04-23  本文已影响0人  KevenT
现有dogs.plist文件如下
dogs.plist

1.如何加载plist文件呢?

- (IBAction)loadPlistBtn:(id)sender {
    //获取bundle
    NSBundle *bundle = [NSBundle mainBundle];
    //获取plist地址
    NSString *path = [bundle pathForResource:@"dogs" ofType:@"plist"];
    //加载plist文件
    NSArray *array = [NSArray arrayWithContentsOfFile:path];
    
    for (NSDictionary *dic in array) {
        NSLog(@"%@----%@---%@",dic[@"name"],dic[@"age"],dic[@"icon"]);
    }
}

2.数据懒加载

按照上面的方式打印,每次都得解析plist读取文件,懒加载如何实现呢?

@interface ViewController ()
@property (nonatomic,strong) NSArray *dogs;//小狗数组
@end


@implementation ViewController
- (NSArray *)dogs{
    if (_dogs==nil) {
        _dogs = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dogs" ofType:@"plist"]];
    }
    return _dogs;
}
- (IBAction)loadPlistBtn:(id)sender {
    for (NSDictionary *dic in self.dogs) {
        NSLog(@"%@----%@---%@",dic[@"name"],dic[@"age"],dic[@"icon"]);
    }
}
@end

这样每次点击的时候只会在首次解析plist文件,后面直接使用第一次读取到的内容

3.数据模型

直接通过字典去读取内容会存在很多问题,不管是本地数据还是网络数据最好的方式应该是通过模型去加载

\color{#EEB422}{模型取代字典的好处}

\color{#EEB422}{创建dog模型}
(1)创建的dog.h

#import <Foundation/Foundation.h>

@interface Dog : NSObject
@property (nonatomic,copy) NSString *name;//姓名
@property (nonatomic,copy) NSString *age;//年龄
@property (nonatomic,copy) NSString *icon;//照片

- (instancetype) initWithDict:(NSDictionary *) dict;
+ (instancetype) dogWithDict:(NSDictionary *) dict;
@end

(2)创建的dog.m

#import "Dog.h"

@implementation Dog

- (instancetype)initWithDict:(NSDictionary *)dict
{
    if (self == [super init]) {
        self.name = dict[@"name"];
        self.age = dict[@"age"];
        self.icon = dict[@"icon"];
    }
    return self;
}

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

(3)修改后的ViewController.m

@interface ViewController ()
@property (nonatomic,strong) NSArray *dogs;//小狗模型数组
@end


@implementation ViewController
- (NSArray *)dogs{
    if (_dogs==nil) {
        //拿到字典数组
        NSArray *dictArray = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"dogs" ofType:@"plist"]];
        //创建小狗模型空数组
        NSMutableArray *dogArray = [NSMutableArray array];
        //遍历字典数组转为模型数组
        for (NSDictionary *dict in dictArray) {
            Dog *dog = [Dog dogWithDict:dict];//创建模型
            [dogArray addObject:dog];//添加到模型数组
        }
        _dogs = dogArray;//赋值
    }
    return _dogs;
}
- (IBAction)loadPlistBtn:(id)sender {
    for (int i=0;i<self.dogs.count;i++) {
        Dog *dog = self.dogs[i];
        NSLog(@"%@----%@",dog.name,dog.icon);
    }
}
@end
上一篇 下一篇

猜你喜欢

热点阅读