iOS開發之如何加載plist文件

一、什麼是plist文件?

        在作iOS開發時,咱們應該常常會用到plist文件,那麼什麼是plist文件呢?它全名是Property List,屬性列表文件,它是一種用來存儲串行化後的對象的文件。屬性列表文件的擴展名爲.plist ,所以一般被稱爲 plist文件。文件是xml格式的。plist文件一般用於儲存用戶設置,也能夠用於存儲捆綁的信息,例如工程中的Info.plist文件。相似於android中的SharedPreferences。android


二、讀取plist文件中的數據

- (void)viewDidLoad {
    [super viewDidLoad];
    //我這裏plist文件名爲shop.plist
    
    //利用mainBundle來關聯主資源包
    NSBundle *bundle = [NSBundle mainBundle];
    
    //獲取plist文件所在的全路徑
    NSFile *file = [bundle pathForResource:@"shop" ofType:@"plist"];
    //也能夠是這樣[bundle pathForResource:@"shop.plist" ofType:nil]
    
    //根據全路徑獲得一個數組對象,裏面就是plist文件中的內容
    NSArray *dictArray = [NSArray arrayWithContentsOfFile:file];
    
    //打印數據
    NSLog(@"%@", dictArray);
}


三、寫入數據到plist文件(先保存,後面再補充吧)數組

//plist的存儲
     
     NSArray *arr = @[@"111", @"222"];
    
    //獲取Caches文件夾
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    
    //拼接文件名
    NSString *filePath = [cachePath stringByAppendingPathComponent:@"demo.plist"];
    
    [arr writeToFile:filePath atomically:YES];
相關文章
相關標籤/搜索