The plist file is a lightweight database for storing smaller data. Here is the basic operation for plist.
Create a new plist file
I am here to create a new one with the whole as Array,item is a dictionary of plist files.
In general development, if you want to manipulate the plist file. is to put the plist file in the sandbox (document) directory
Get the Resource directory first:
// Get the Resource directory (new plist file)-(NSString *) Getdatasourcepath: (NSString *) sourceName andtype: (NSString *) filetype{ *path = [[nsbundle Mainbundle] Pathforresource:sourcename oftype:filetype]; return path;}
Get the Sandbox (Document)
// Get Documents Catalogue -(NSString *) Getdocumentpath: (NSString *) filename{ // Two ways to get the document path // nsstring *documents = [Nshomedirectory () stringbyappendingpathcomponent:@ "Documents"]; *paths = nssearchpathfordirectoriesindomains (nsdocumentdirectory, Nsuserdomainmask, YES); *documents = [paths Objectatindex:0]; *path = [documents Stringbyappendingpathcomponent:filename]; return path;}
Focus:
Get sandbox plist file
NSString *documentpath = [self getdocumentpath:@ "Szplistdemo.plist"];
Add data to the document directory 1: Direct Write, 2: Copy the resource file to the documents directory under /c12>
The first method:
// nserror *error; // if ([Plistpath writetofile:documentpath atomically:yes encoding:nsutf8stringencoding Error:&error]) { // NSLog (@ "File write success. "); // }else{// NSLog (@ "Error =%@", error); // }
The second type:
//2: Copy to the documents directoryNsfilemanager *manager =[Nsfilemanager Defaultmanager]; Nserror*error; if([manager Fileexistsatpath:documentpath]) {NSLog (@"file is exists"); }Else{ if([Manager Copyitematpath:plistpath Topath:documentpath error:&ERROR]) {NSLog (@"file is not exists, copy success!"); }Else{NSLog (@"error =%@", error); return; } }
Write data like plist
// get the data from the resource directory
Nsmutablearray *documentdata =[[Nsmutablearray alloc] initwithcontentsoffile:documentpath]; NSLog (@"Documentdata =%@", Documentdata); Nsdictionary*dic = @{@" Age":@" -",@"Phone_num":@"1328820394"}; [Documentdata Addobject:dic];
Write file
[Documentdata writetofile:documentpath atomically:YES];
Delete plist file
Here I use a button, click the button to delete the plist file
Nserror *error; *filemanager = [Nsfilemanager Defaultmanager]; if ([FileManager Removeitematpath:documentpath error:&Error]) { NSLog (@ "remove success! " ); } Else { NSLog (@ "error =%@", error); }