通過plist檔案存取檔案
在 ios檔案處理(一)的項目中,修改HomeViewController.m的viewDidLoad方法
- (void)viewDidLoad
{/* NSString *fileName = [[self documentsPath] stringByAppendingPathComponent:@"content.txt"]; //NSString *fileName = [[self tempPath] stringByAppendingPathComponent:@"content.txt"]; [self writeToFile:@"蘋果的魅力!" withFileName:fileName]; NSString *fileContent = [self readFromFile:fileName]; NSLog(fileContent);*/ NSString *fileName = [[self tempPath] stringByAppendingPathComponent:@"content.txt"]; [self writeToFile:@"我愛蘋果!" withFileName:fileName]; NSString *fileContent = [self readFromFile:fileName];
//操作plist檔案,首先擷取在Documents中的contacts.plist檔案全路徑,並且把它賦值給plistFileName變數。
NSString *plistFileName = [[self documentsPath] stringByAppendingPathComponent:@"contacts.plist"]; if ([[NSFileManager defaultManager] fileExistsAtPath:plistFileName]) {
//載入字典中
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistFileName];
//按照類別顯示在偵錯主控台中
for (NSString *category in dict) { NSLog(category); NSLog(@"********************"); NSArray *contacts = [dict valueForKey:category]; for (NSString *contact in contacts) { NSLog(contact); } } [dict release]; } else {//如果Documents檔案夾中沒有contacts.plist檔案的話,則從專案檔中載入contacts.plist檔案。 NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"contacts" ofType:@"plist"]; NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
//寫入Documents檔案夾中
fileName = [[self documentsPath] stringByAppendingPathComponent:@"contacts.plist"]; [dict writeToFile:fileName atomically:YES]; [dict release]; } [super viewDidLoad];}
:
P.S:
我們有時會用到綁定資源 (通常將項目中的資源叫綁定資源,他們都是唯讀。如果我們想在應用程式啟動並執行時候對這些資源進行讀寫操作,就需要將它們複製到應用程式檔案夾中,比如Documents和tmp檔案夾)
在 AppDelegate.m中添加一個方法即可
//複製綁定資源
//原理:我們首先擷取應用程式的Documents檔案夾的位置,然後在Documents中搜尋通過該方法參數傳遞進來的檔案名稱,其中包括檔案名稱和副檔名。如果該檔案不存在,則通過NSBundle類直接擷取該綁定資源並將其複製到Documents檔案夾中- (void) copyBundleFileToDocumentsFolder:(NSString *)fileName withExtension:(NSString *)ext{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithString:fileName]]; filePath = [filePath stringByAppendingString:@"."]; filePath = [filePath stringByAppendingString:ext]; [filePath retain]; NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:filePath]) { NSString *pathToFileInBundle = [[NSBundle mainBundle] pathForResource:fileName ofType:ext]; NSError *error = nil; bool success = [fileManager copyItemAtPath:pathToFileInBundle toPath:filePath error:&error]; if (success) { NSLog(@"檔案已複製"); } else { NSLog([error localizedDescription]); } }
}