iphone - Adding a new dictionary to my plist file -


root ---- array
  item 0- dictionary
    fullname ---- string
    address ---- string
  item 1 ---- dictionary
    fullname ---- string
    address ---- string

have plist looks 1 about. in view have button when clicked i'd add new "item 2" or 3 or 4 or 5 etc... want add few more names , addresses.

i've spent 3 hours tonight searching perfect example came short. apple property lists samples way deep. i've seen code come close.

thanks

nsmutabledictionary *namedictionary = [nsmutabledictionary dictionary]; [namedictionary setvalue:@"john doe" forkey:@"fullname"]; [namedictionary setvalue:@"555 w 1st st" forkey:@"address"];

nsmutablearray *plist = [nsmutablearray arraywithcontentsoffile:[self datafilepath]]; [plist addobject:namedictionary]; [plist writetofile:[self datafilepath] atomically:yes]; 

- (nsstring *)datafilepath { nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes); nsstring *documentsdirectory = [paths objectatindex:0]; nsstring *path = [documentsdirectory stringbyappendingpathcomponent:@"children.plist"]; return path; }

assuming plist stored on disk file, can reopen , load new contents calling arraywithcontentsoffile method.

// create new dictionary inserted plist. nsmutabledictionary *namedictionary = [nsmutabledictionary dictionary]; [namedictionary setvalue:@"john doe" forkey:@"fullname"]; [namedictionary setvalue:@"555 w 1st st" forkey:@"address"];  // open plist filesystem. nsmutablearray *plist = [nsmutablearray arraywithcontentsoffile:@"/path/to/file.plist"]; if (plist == nil) plist = [nsmutablearray array]; [plist addobject:namedictionary]; [plist writetofile:@"/path/to/file.plist" atomically:yes]; 

the -(void)addobject:(id)object inserts @ end of array. if need insert @ specific index use -(void)insertobject:(id)object atindex:(nsuinteger)index method.

[plist insertobject:namedictionary atindex:2]; 

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -