When a user signs in through my iPhone app, I create a bunch of default elements in the NSUserDefaults. One of these is an NSMutableArray that I add the following way:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSMutableArray *theArray = [NSMutableArray array];
[prefs setObject:theArray forKey:@"t开发者_高级运维heArray"];
This works flawlessly. However, when I want to insert or retrieve values from theArray
, something goes wrong. Here's an excerpt from another file in my app:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[[prefs objectForKey:@"theArray"] setValue:@"This is a value" forKey:@"aValue"];
NSLog(@"%@", [[prefs objectForKey:@"theArray"] valueForKey:@"aValue"]);
I would expect to see "This is a value" in the console when the code has run, but instead I get this:
2011-08-08 18:35:17.503 MyApp[7993:10d03] (
)
How come the array is empty? I've tried the same thing using an NSArray with the same result.
When you store mutable objects to NSUserDefaults, it stores an immutable copy of it so you can't change it directly like that. You have to get the mutable copy out of defaults, change it, and then set it back, replacing old object in defaults.
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSMutableArray *mutableArrayCopy = [[prefs objectForKey:@"theArray"] mutableCopy];
[mutableArrayCopy addObject:@"some new value"];
[prefs setObject:mutableArrayCopy forKey:@"theArray"];
[mutableArrayCopy release];
NSArray *savedArray = [NSArray arrayWithObjects:@"obj1",@"obj2",@"obj3", nil];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:savedArray forKey:@"key_for_savedArray"];
[userDefaults synchronize];
//To retrive array use:
NSArray *retrivedArray = [userDefaults objectForKey:@"key_for_savedArray"];
精彩评论