I've been experiencing very inconsistent results while developing an iPhone app and trying to save preferences via the standard NSUserDefaults mechanism. I am using code almost straight out of the iPhone Developer's Cookbook by Erica Sadun (fantastic book btw), it looks like this:
(void) updateDefaults { NSMutableArray *spells = [[NSMutableArray alloc] init]; NSMutableArray *locs = [[NSMutableArray alloc] init]; for (DragView *dv in [boardView subviews]) { [spells addObject:[dv whichSpell]]; [locs addObject:NSStringFromCGRect([dv frame])]; } [[NSUserDefaults standardUserDefaults] setObject:spells forKey:@"spells"]; [[NSUserDefaults standardUserDefaults] setObject:locs forKey:@"locs"]; [[NSUserDefaults standardUserDefaults] synchronize]; [spells release]; [locs release]; }
The values are saved, sometimes…and restored, sometimes. I can't get an exact bead on what does or does not make it work.
Does anyone else have any similar experiences? Any suggestions on what might make it work? Is the synchronize method the best way to force a disk write and make the values save, or is there something better (both for production, as well as simulator).
Thanks
Ryan
Best Answer
You should be using an NSKeyedArchiver for saving your arrays, such as:
You should also make sure your spells class implements the NSCoding protocol (encodeWithCoder: and initWithCoder:), if it's a custom class. It looks like your locs are NSStrings, which will archive just fine.
You'll also need to do something like
To load the old values from the defaults.
I use synchronize to write to disk on exit, and it's been very reliable in my experience.