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];NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager removeItemAtPath:documentPath error:&error]) {
NSLog(@"remove success!");
} else {
NSLog(@"error = %@", error);
}掌握以上操作,就能靈活地在 iOS 中透過 Plist 檔案進行輕量級的資料持久化。