資料持久化-Plist檔案寫入,-plist寫入
資料持久化,常見4種:歸檔,plist檔案,sqlite,coreData.今天複習的是plist檔案讀寫.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
// // ViewController.m // Test_Plist // // Created by lidongbo on 14/10/30. // Copyright (c) 2014年 lidongbo. All rights reserved. // #import "ViewController.h" @interface ViewController () @end @implementation ViewController - ( void )viewDidLoad { [ super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. /* 讀取plist檔案的內容. */ NSString * path = [[ NSBundle mainBundle] pathForResource:@ "Person" ofType:@ "plist" ]; NSMutableDictionary * data = [[ NSMutableDictionary alloc] initWithContentsOfFile:path]; NSLog (@ "%@" ,data); /* 擷取Document檔案夾中plist檔案的路徑 */ NSMutableArray * mArr = [[ NSMutableArray alloc] initWithObjects:@ "英語" ,@ "資料" ,@ "法語" ,@ "日語" ,@ "德語" , nil ]; NSArray *paths = NSSearchPathForDirectoriesInDomains ( NSDocumentDirectory , NSUserDomainMask , YES ); NSString * plistPath = [paths objectAtIndex:0]; NSLog (@ "%@" ,plistPath); // NSString * fileName = [plistPath stringByAppendingString:@"/Person.plist"]; NSString * fileName = [plistPath stringByAppendingPathComponent:@ "Person.plist" ]; /* 賦值 */ [data setObject:mArr forKey:@ "kemu" ]; [data setObject:@ "14" forKey:@ "age" ]; /* plist檔案寫入 */ [data writeToFile:fileName atomically: YES ]; NSMutableDictionary * data1 = [[ NSMutableDictionary alloc] initWithContentsOfFile:fileName]; NSLog (@ "%@" ,data1); /* plist檔案可以多次寫入. */ NSMutableArray * mmArr = [[ NSMutableArray alloc] initWithObjects:@ "1" ,@ "2" ,@ "3" , nil ]; [data setObject:mmArr forKey:@ "kemu" ]; [data writeToFile:fileName atomically: YES ]; NSMutableDictionary * data2 = [[ NSMutableDictionary alloc] initWithContentsOfFile:fileName]; NSLog (@ "______%@" ,data2); } - ( void )didReceiveMemoryWarning { [ super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end |