您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 資料持久化(一):以屬性列表 plist 保存資料

編輯:iOS 相關資訊

iOS 中常見的資料持久化方式有五種:屬性列表(Property List)、物件歸檔(NSCoding)、NSUserDefaults、SQLite3 與 Core Data。本文聚焦最基礎也最常用的一種——plist。

App 的設定與個人化選項,多半就是靠 plist 存放與讀取。

一、取得沙盒路徑

FOUNDATION_EXPORT NSArray *NSSearchPathForDirectoriesInDomains(
    NSSearchPathDirectory directory,
    NSSearchPathDomainMask domainMask,
    BOOL expandTilde);

這個函式會建立一個目錄搜尋路徑清單,回傳指定域中某個目錄的路徑字串陣列,陣列順序即為你應該搜尋的順序。

要注意的是:回傳的路徑可能實際上並不存在。這個函式只負責告訴你「該目錄應該在哪裡」,是否建立則由開發者依需求決定。在 iOS 上,此函式回傳的陣列通常只有一個元素。

二、封裝一個 Plist 工具類別

// Plist.h
@interface Plist : NSObject
- (void)modifyData:(NSString *)dataKey Value:(NSString *)dataValue;
- (void)deleteDataWithDataKey:(NSString *)key;
@end
// Plist.m
@implementation Plist

- (id)init {
    if (self = [super init]) {
        NSString *documents =
            [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
                objectAtIndex:0];
        NSString *plistPath = [documents stringByAppendingPathComponent:@"student.plist"];

        if ([[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
            NSLog(@"student.plist 已存在");
        } else {
            NSMutableDictionary *rootDic = [[NSMutableDictionary alloc] init];
            NSMutableDictionary *subDic = [[NSMutableDictionary alloc] init];
            [rootDic setObject:subDic forKey:@"student"];
            [rootDic writeToFile:plistPath atomically:YES];
        }
    }
    return self;
}

init 中先判斷檔案是否存在,若不存在就以一個空的字典骨架建立,這樣後續的修改方法就不必處理 nil。

三、寫入與修改

- (void)modifyData:(NSString *)dataKey Value:(NSString *)dataValue {
    NSString *path = [[NSSearchPathForDirectoriesInDomains(
        NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
        stringByAppendingPathComponent:@"student.plist"];

    // 讀出 → 轉為可變 → 修改 → 整份寫回
    NSMutableDictionary *rootDic = [[[NSMutableDictionary alloc]
        initWithContentsOfFile:path] mutableCopy];
    NSMutableDictionary *studentInfo = [rootDic objectForKey:@"student"];
    [studentInfo setValue:dataValue forKey:dataKey];

    [rootDic writeToFile:path atomically:YES];
}

plist 沒有「局部更新」的概念,每次修改都要走「讀出、改記憶體、整份寫回」的流程。這也是為什麼 plist 不適合存放大量資料。

四、刪除

- (void)deleteDataWithDataKey:(NSString *)key {
    NSString *path = [[NSSearchPathForDirectoriesInDomains(
        NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
        stringByAppendingPathComponent:@"student.plist"];

    NSMutableDictionary *rootDic = [[[NSMutableDictionary alloc]
        initWithContentsOfFile:path] mutableCopy];
    NSMutableDictionary *studentInfo = [rootDic objectForKey:@"student"];
    [studentInfo removeObjectForKey:key];
    [rootDic setValue:studentInfo forKey:@"student"];
    [rootDic writeToFile:path atomically:YES];
}

五、在控制器中使用

- (IBAction)addOrModifyTapped:(id)sender {
    if (![_keyTF.text isEqualToString:@""] && ![_valueTF.text isEqualToString:@""]) {
        [_plistFile modifyData:_keyTF.text Value:_valueTF.text];
    }
}

- (IBAction)deleteTapped:(id)sender {
    if (![_deleteKeyTF.text isEqualToString:@""]) {
        [_plistFile deleteDataWithDataKey:_deleteKeyTF.text];
    }
}

六、這個實作可以改進的地方

1. 把路徑計算抽成一個方法。 目前三個方法各自重複一次路徑組裝,應集中為 - (NSString *)plistPath,日後要換目錄只需改一處。

2. ARC 下請移除所有 release。 原範例寫於 MRC 時代,mutableCopy 之後忘了 release 會造成記憶體洩漏,而在 ARC 專案中根本無法編譯。

3. 選擇合適的保存機制。 如果只是幾個設定值,直接用 NSUserDefaults 更合適;若資料有結構與關聯、需要查詢與排序,則該改用 Core Data 或 SQLite。plist 的定位是「少量、結構簡單、可整份讀寫」的資料。

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