直接将数据直接写在代码里面,不是一种合理的作法。若是数据常常改,就要常常翻开对应的代码进行修改, 形成代码扩展性低。数组
所以,能够考虑将常常变的数据放在文件中进行存储,程序启动后从文件中读取最新的数据。若是要变更数 据,直接修改数据文件便可,不用修改代码。xcode
通常可使用属性列表文件存储 NSArray 或者 NSDictionary 之类的数据,这种属性列表文件的扩展名是 plist, 所以也成为“Plist 文件”。网络
在建立 Plist 文件的时候要特别注意名称当中不能带“info”,若是带了“info”会致使 xcode 把它误看成一个项 目中某个文件而出现问题。,致使文件加载不进来。学习
(1)得到 Plist 文件的全路径url
NSBundle *bundle = [NSBundle mainBundle]; NSString *path = [bundle pathForResource:@"imageData(文件名)" ofType:@"plist(扩展名)"];
(2)加载 plist 文件spa
//若是从网络加载能够用: //_images = [NSArray arrayWithContentsOfUrl:url]; _images = [NSArray arrayWithContentsOfFile:path]; - (NSArray *)images { if (_images == nil) { //能够利用 mainBundle 获取手机里面的任何资源 NSBundle *bundle = [NSBundle mainBundle]; NSString *path = [bundle pathForResource:@"imageData" ofType:@"plist"]; self.imageData = [NSArray arrayWithContentsOfFile:path]; } return _images; }
打印项目所在Mac的路径:code
// 得到项目的路径 NSBundle *bundle = [NSBundle mainBundle]; NSLog(@"%@", bundle);
得到项目目录下的plist文件路径blog
// 得到项目目录下的plist文件路径 NSString *path = [bundle pathForResource:@"images" ofType:@"plist"]; NSLog(@"%@", path);
plist添加数据:
Root为数组类型,里边包含两个字典索引
完整代码:ip
// // ViewController.m // 02-plist学习 // // Created by kaiyi wang on 16/8/25. // Copyright © 2016年 Corwien. All rights reserved. // #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 1.得到plist文件的全路径 NSBundle *bundle = [NSBundle mainBundle]; NSString *path = [bundle pathForResource:@"images" ofType:@"plist"]; // NSLog(@"%@", path); NSArray *myPlist = [NSArray arrayWithContentsOfFile:path]; NSLog(@"%@", myPlist); // 打印plist // NSNumber *num = @0; // 获取数组的第一个元素,字典类型 NSDictionary *mydict = [myPlist objectAtIndex:0]; NSLog(@"%@", mydict[@"name"]); } @end
打印结果:
是把 plist 文件转成一个 NSArray,里面存放各 Dictionary。之后能够根据索引从 dictArray 中取出对应 Dictionary, 再根据字段取出对应数据。