直接將數據直接寫在代碼裏面,不是一種合理的作法。若是數據常常改,就要常常翻開對應的代碼進行修改, 形成代碼擴展性低。數組
所以,能夠考慮將常常變的數據放在文件中進行存儲,程序啓動後從文件中讀取最新的數據。若是要變更數 據,直接修改數據文件便可,不用修改代碼。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, 再根據字段取出對應數據。