objective c - (iOS) Reading a plist from Documents folder - I get correct path but can't load dictionary -
i know there tons of threads on issue, cannot seem find 1 solves problem. have plist dictionary root, containing 3 arrays. code write plist works fine in simulator (null) on device.
- i'm not trying write app bundle,
my file path correct , checking @ launch make sure file exists in documents folder (and exist).
- (void) writetoplist:(nsstring *)filename playercolor:(nsstring *)player withdata:(nsarray *)data { nsarray *syspaths = nssearchpathfordirectoriesindomains(nsdocumentdirectory ,nsuserdomainmask, yes); nsstring *documentsdirectory = [syspaths objectatindex:0]; nsstring *filepath = [documentsdirectory stringbyappendingpathcomponent:filename]; nslog(@"file path: %@", filepath); nsdictionary *plistdict = [[nsdictionary alloc] initwithcontentsoffile:filepath]; nslog(@"plist: %@", [plistdict description]); [plistdict setvalue:data forkey:player]; bool didwritetofile = [plistdict writetofile:filepath atomically:yes]; if (didwritetofile) { nslog(@"write file success!"); } else { nslog(@"write file failure!"); } }
debug output:
file path: /var/mobile/applications/ca9d8884-2e92-48a5-aa73-5252873d2571/documents/currentscores.plist plist: (null) write file failure!
i've used same method in other projects, don't know if i'm forgetting or deal is. i've checked spelling/capitalization , remade plist, neither made difference.
so why plistdict (null) on device, not on simulator? apologize if missed solution in post on plists.
your code written assume file exists in documents
folder. won't case first time method ever called.
you should add check existence of file. if it's there, load it. if not, other proper initialization of data in preparation writing.
also, dictionary needs mutable change or add keys/values.
- (void) writetoplist:(nsstring *)filename playercolor:(nsstring *)player withdata:(nsarray *)data { nsarray *syspaths = nssearchpathfordirectoriesindomains(nsdocumentdirectory ,nsuserdomainmask, yes); nsstring *documentsdirectory = [syspaths objectatindex:0]; nsstring *filepath = [documentsdirectory stringbyappendingpathcomponent:filename]; nslog(@"file path: %@", filepath); nsmutabledictionary *plistdict; // needs mutable if ([[nsfilemanager defaultmanager] fileexistsatpath:filepath]) { plistdict = [[nsmutabledictionary alloc] initwithcontentsoffile:filepath]; } else { // doesn't exist, start empty dictionary plistdict = [[nsmutabledictionary alloc] init]; } nslog(@"plist: %@", [plistdict description]); [plistdict setvalue:data forkey:player]; bool didwritetofile = [plistdict writetofile:filepath atomically:yes]; if (didwritetofile) { nslog(@"write file success!"); } else { nslog(@"write file failure!"); } }
Comments
Post a Comment