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

IOS Plist 檔案儲存教學

編輯:iOS 開發綜合

iOS 每個 App 都有自己的文件系統,常見目錄包括 Documents、tmp、Library/Caches 與 Library/Preferences。Plist 常用來儲存簡單結構資料。

取得路徑

NSString *homePath = NSHomeDirectory();
NSString *docPath = [homePath stringByAppendingPathComponent:@"Documents"];

NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSAllDomainsMask, YES);
NSArray *cachePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSAllDomainsMask, YES);
NSString *tempPath = NSTemporaryDirectory();

儲存 Array 到 Plist

NSArray *arr = @[@"name", @"age", @"height"];
NSString *filePath = [docPath stringByAppendingPathComponent:@"aa.plist"];
[arr writeToFile:filePath atomically:YES];

NSArray *arr2 = [NSArray arrayWithContentsOfFile:filePath];

儲存 Dictionary 到 Cache

NSDictionary *dic = @{@"name": @"lean", @"age": @24, @"height": @172};
NSString *cachePath = [cachePaths objectAtIndex:0];
NSString *dicPath = [cachePath stringByAppendingPathComponent:@"dic.plist"];
[dic writeToFile:dicPath atomically:YES];

NSDictionary *dic2 = [NSDictionary dictionaryWithContentsOfFile:dicPath];

儲存圖片

圖片不能直接寫入 Plist,需要先轉成 NSData。

NSData *data = UIImageJPEGRepresentation(image, 1);
[data writeToFile:filePath atomically:YES];

NSData *data2 = [NSData dataWithContentsOfFile:filePath];
UIImage *image2 = [UIImage imageWithData:data2];

Plist 只能儲存 NSString、NSNumber、NSData、NSArray 與 NSDictionary 等型別。

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