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

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

編輯:iOS 相關資訊

Plist 檔案是一個輕量級的資料庫,適合用來存放一些比較小的資料。本文整理 Plist 檔案的讀取、寫入與刪除等基本操作。

取得檔案路徑

一般開發中,若要操作 Plist 檔案,通常會先把它放到沙盒(Documents)目錄下。首先要能取得資源目錄與沙盒目錄:

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

// 得到 documents 目錄
- (NSString *)getDocumentPath:(NSString *)fileName {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [paths objectAtIndex:0];
    NSString *path = [documents stringByAppendingPathComponent:fileName];
    return path;
}

將檔案放入沙盒

有兩種方式可以將 Plist 檔案放進 Documents 目錄:直接寫入,或將資源檔複製過去。

方式一:直接寫入

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;
    }
}

寫入資料

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

NSDictionary *dic = @{@"age": @"25", @"phone_num": @"1328820394"};
[documentData addObject:dic];
// 寫入檔案
[documentData writeToFile:documentPath atomically:YES];

刪除 Plist 檔案

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

掌握以上操作,就能靈活地在 iOS 中透過 Plist 檔案進行輕量級的資料持久化。

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