您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發:Plist 檔案的基本操作

編輯:iOS 開發綜合

plist 是一個輕量級的資料儲存格式,適合存放體積不大的結構化資料,例如設定項、少量清單。以下整理新增、讀寫、刪除的完整流程。

這裡建立的是一個外層為 Array、每個元素為 Dictionary 的 plist。

取得檔案路徑

一般開發中,要操作 plist 都會先把它放到沙盒的 Documents 目錄下,因為 App bundle 內的資源是唯讀的。

先取得資源(bundle)目錄:

// 取得資源目錄中的 plist
- (NSString *)getDataSourcePath:(NSString *)sourceName andType:(NSString *)fileType {
    NSString *path = [[NSBundle mainBundle] pathForResource:sourceName ofType:fileType];
    return path;
}

再取得沙盒的 Documents 目錄:

// 取得 Documents 目錄
- (NSString *)getDocumentPath:(NSString *)fileName {
    // 兩種取得方式
    // NSString *documents = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [paths objectAtIndex:0];
    NSString *path = [documents stringByAppendingPathComponent:fileName];
    return path;
}

重點:把 plist 放進沙盒

NSString *documentPath = [self getDocumentPath:@"szPlistDemo.plist"];

有兩種做法:直接寫入,或把資源檔複製過去。

方法一:直接寫入

NSError *error;
if ([plistPath writeToFile:documentPath atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
    NSLog(@"file write success .");
} else {
    NSLog(@"error = %@", error);
}

方法二:複製到 Documents 目錄

NSFileManager *manager = [NSFileManager defaultManager];
NSError *error;

if ([manager fileExistsAtPath:documentPath]) {
    NSLog(@"file is exists");
} else {
    if ([manager copyItemAtPath:plistPath toPath:documentPath error:&error]) {
        NSLog(@"file is not exists, copy success!");
    } else {
        NSLog(@"error = %@", error);
        return;
    }
}

方法二在實務上更常見:第一次啟動時把隨包的預設值複製一份到沙盒,之後所有讀寫都只針對沙盒那份,重新安裝 App 時預設值永遠是乾淨的。

寫入資料

NSMutableArray *documentData = [[NSMutableArray alloc] initWithContentsOfFile:documentPath];
NSLog(@"documentData = %@", documentData);

NSDictionary *dic = @{@"age": @"25", @"phone_num": @"1328820394"};
[documentData addObject:dic];

// 寫回檔案
[documentData writeToFile:documentPath atomically:YES];

注意 initWithContentsOfFile: 讀出來的是不可變內容,所以要用 NSMutableArray 承接才能修改。

刪除檔案

這裡用一個按鈕觸發刪除:

NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];

if ([fileManager removeItemAtPath:documentPath error:&error]) {
    NSLog(@"remove success!");
} else {
    NSLog(@"error = %@", error);
}

最後提醒兩點:atomically:YES 會先寫入暫存檔再取代目標檔,能避免寫入中途被中斷而導致檔案損毀,建議一律保留;另外 plist 不適合存放大量資料或巢狀層數過深的結構,若資料量持續成長,應及早改用 Core Data 或 SQLite。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved