Data Persistence-write a Plist file and write a plist File
Data Persistence: four common types: Archive, plist file, sqlite, and coreData. Today we are reviewing plist file read/write.
//// 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. /* read the content of the plist file. */NSString * path = [[NSBundle mainBundle] pathForResource: @ "Person" ofType: @ "plist"]; NSMutableDictionary * data = [[NSMutableDictionary alloc] initWithContentsOfFile: path] NSLog (@ "% @", data);/* obtain the path of the plist file in the Document folder */NSMutableArray * mArr = [[NSMutableArray alloc] initWithObjects: @ "English ", @ "data", @ "French", @ "Japanese", @ "German", 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 "];/* value */[data setObject: mArr forKey: @" kemu "]; [data setObject: @" 14 "forKey: @" age "]; /* plist file write */[data writeToFile: fileName atomically: YES]; NSMutableDictionary * data1 = [[NSMutableDictionary alloc] initWithContentsOfFile: fileName]; NSLog (@ "% @", data1);/* plist files can be written multiple times. */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) didreceivemorywarning {[super didreceivemorywarning]; // Dispose of any resources that can be recreated .} @ end
How to Write a plist file?
It is correct to find that the plist file in the project has not been changed because the plist file in the project is packaged in. app, with the code signature, is read-only note this sentence: NSString * Path = [NSString stringWithFormat: @ "% @ data. plist ", NSTemporaryDirectory ()]; NSTemporaryDirectory () is written. You can print it using NSLog to see where the Temp directory is located, let's take a look at the concept and principles of SandBox/SandBox ~
How to Write plist files in iphone Development
First, your data is stored in a dictionary, that is, NSDictionary. There is a method-writeToFile: atomically:
[Dict writeToFile: @ "your path/xxx. plist" atomically: YES];
Read it as follows:
Dict = [NSdictionary dictionaryWithContentsOfFile: @ "your path"];