Inappropriate default behavior (NSUserDefaults) in the default iPhone simulator

I had very inconsistent results when developing an application for the iPhone and trying to save the settings using the standard NSUserDefaults mechanism. I use the code almost directly from Erica Sadun's iPhone Developers Cookbook (a fantastic book by the way), 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];
}

Values ​​are saved, sometimes ... and sometimes restored. I can’t get the exact letter about what her job is doing or not doing.

Does anyone have any other similar experiences? Any suggestions on what might make it work? Is the synchronization method the best way to force the disc to write and save the values, or is there something better (both for production and for the simulator)

Thanks Ryan

+5
source share
2 answers

You should use NSKeyedArchiver to save your arrays, for example:

[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:spells] forKey:@"spells"];
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:locs] forKey:@"locs"];
[[NSUserDefaults standardUserDefaults] synchronize];

, NSCoding (encodeWithCoder: initWithCoder:), . , - NSStrings, .

-

NSData *dataRepresentingSavedSpells = [currentDefaults objectForKey:@"spells"];
if (dataRepresentingSavedSpells != nil)
{
    NSArray *oldSpells = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedSpells];
}

.

, .

+2

Mac OS X , , iPhone OS : NSString, NSNumber, NSArray, NSDictionary NSData.

, , , . :

  • , plist . , NSDictionary NSDictionary. NSArray NSString.
  • NSCoding, NSKeyedArchiver NSData NSKeyedUnarchiver .
+2

All Articles