廢話少說,直接上代碼:
(void)viewDidLoad { [super viewDidLoad]; //讀取plist文件在程序文件夾中的文件,並且要注意,程序文件的文件只能讀不能寫,只能在程序沙盒之中; NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"plisttest" ofType:@"plist"]; NSLog(@"這是plist文件的路徑%@", plistPath); NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath]; NSLog(@"這是plist文件的內容%@", data); //添加數據說明,可以進行修改; [data setObject:@"我在東北大學" forKey:@"address"]; [data setObject:@"男" forKey:@"sex"]; //獲取應用沙盒的的DOCUMENT 的路徑; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString* plistPath1 = [paths objectAtIndex:0]; //在此處設置文件的名字補全其中的路徑, 注意對於文件內存的修改是在內存之中完成的,然後直接把現在的數據一次性更新,這樣減少了文件的讀寫的次數 NSString *filename =[plistPath1 stringByAppendingPathComponent:@"plisttest.plist"]; NSLog(@"這是沙盒之中的路徑%@", filename); //寫入文件 [data writeToFile:filename atomically:YES]; NSLog(@"證明我的數據真正得寫入在其中了"); //證明文件寫入成功 NSMutableDictionary *afterData = [[NSMutableDictionary alloc] initWithContentsOfFile:filename]; NSLog(@"這是寫入過數據的情況%@", afterData); NSLog(@"程序結束"); // Do any additional setup after loading the view, typically from a nib. }
2015-04-26 12:08:55.857 plist[1702:112934] 這是plist文件的路徑/Users/xuyaowen/Library/Developer/CoreSimulator/Devices/6BD2A547-CC45-4739-9578-C1D268C26B20/data/Containers/Bundle/Application/28977EA1-0F6A-4B4F-AF37-F6BADEEB889C/plist.app/plisttest.plist 2015-04-26 12:08:55.868 plist[1702:112934] 這是plist文件的內容{ info = "\U8fd9\U662f\U6211\U7684plist\U6587\U4ef6"; name = xiaohongqi; password = xiaohongqi; } 2015-04-26 12:08:55.869 plist[1702:112934] 這是沙盒之中的路徑/Users/xuyaowen/Library/Developer/CoreSimulator/Devices/6BD2A547-CC45-4739-9578-C1D268C26B20/data/Containers/Data/Application/F145B509-73B0-4266-AE06-94F2B0A56A7C/Documents/plisttest.plist 2015-04-26 12:08:55.902 plist[1702:112934] 證明我的數據真正得寫入在其中了 2015-04-26 12:08:55.902 plist[1702:112934] 這是寫入過數據的情況{ address = "\U6211\U5728\U4e1c\U5317\U5927\U5b66"; info = "\U8fd9\U662f\U6211\U7684plist\U6587\U4ef6"; name = xiaohongqi; password = xiaohongqi; sex = "\U7537"; } 2015-04-26 12:08:55.902 plist[1702:112934] 程序結束
然後通過運行結束時的日志內容,證明成功!
用前往文件夾:復制路徑即可訪問到程序沙盒之中的文件,注意提高自身的能力!