creation of plist in iOS, data write and read
09/02/2011function creates a test.plist file, textinput as input, Displaylabel as a display, has a button to trigger the Hold program Triggerstorage;
-(void) triggerstorage
{
Displaylabel.text = Textinput.text;
Nsarray *paths=nssearchpathfordirectoriesindomains (Nsdocumentdirectory,nsuserdomainmask,yes);
NSString *path=[paths objectatindex:0];
NSString *filename=[path stringbyappendingpathcomponent:@ "Test.plist"]; Get path
nsdictionary* Dic2 = [Nsdictionary dictionarywithcontentsoffile:filename]; Reading data
NSLog (@ "Dic2 is:%@", dic2);
Create a dic and write it into the plist file.
nsdictionary* dic = [nsdictionary dictionarywithobjectsandkeys:displaylabel.text,@ "IP", nil]; Write Data
[DiC Writetofile:filename Atomically:yes];
}
Implement Viewdidload to does additional setup after loading the view, typically from a nib.
-(void) viewdidload
{
Nsmutablearray *resultdata;
Nsarray *paths=nssearchpathfordirectoriesindomains (Nsdocumentdirectory,nsuserdomainmask,yes);
NSString *path=[paths objectatindex:0];
NSLog (@ "path =%@", path);
NSString *filename=[path stringbyappendingpathcomponent:@ "Test.plist"];
Read the file
nsdictionary* Dic2 = [Nsdictionary dictionarywithcontentsoffile:filename];
NSLog (@ "dic is:%@", Dic2);
if (Dic2 = = nil)
{
1. Create a plist file
nsfilemanager* fm = [Nsfilemanager Defaultmanager];
[FM createfileatpath:filename Contents:nil Attributes:nil];
}
Else
{
Resultdata=[dic2 objectforkey:@ "IP"];
if ([Dic2 count] > 0)
{
Displaylabel.text = Resultdata;
}
Else
{
Displaylabel.text = @ "";
}
}
Self.navigationItem.rightBarButtonItem = [[[Uibarbuttonitem alloc]//button initialization and trigger condition settings
initwithtitle:@ "Save"
Style:uibarbuttonitemstyleplain
Target:self
Action: @selector (Triggerstorage)] autorelease];
[Super Viewdidload];
}
--------------------------------------------------------------------------------------------------------------- ---------------------------------------------
Reference code:
plist file read/write
1. Create a plist file
Nsarray *paths=nssearchpathfordirectoriesindomains (Nsdocumentdirectory,nsuserdomainmask,yes);
NSString *path=[paths objectatindex:0];
NSLog (@ "path =%@", path);
NSString *filename=[path stringbyappendingpathcomponent:@ "Test.plist"];
nsfilemanager* fm = [Nsfilemanager Defaultmanager];
[FM createfileatpath:filename Contents:nil Attributes:nil];
nsdictionary* dic = [Nsdictionary Dictionarywithcontentsoffile:plistpath];
Create a dic and write it into the plist file.
nsdictionary* dic = [nsdictionary dictionarywithobjectsandkeys:@ "Sina", @ "1", @ "163", @ "2", nil];
[DiC Writetofile:filename Atomically:yes];
Read the file
nsdictionary* Dic2 = [Nsdictionary dictionarywithcontentsoffile:filename];
NSLog (@ "dic is:%@", Dic2);
Creation of plist in iOS, data write and read