Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I store and retrieve an NSMutableDictionary to and from NSUserDefaults?

I tried to do this to store an empty dictionary in NSUserDefaults.

NSMutableDictionary* fruits = [NSMutableDictionary alloc];
[defaults setObject:fruits forKey:@"fruits"];

and then later this to retrieve it.

NSMutableDictionary* fruits = [[NSMutableDictionary alloc] initWithDictionary:[defaults objectForKey:@"fruits"]];

However, retrieving the dictionary crashes my application. Why? How do I store a dictionary in NSUserDefaults?

like image 298
Billy Goswell Avatar asked Dec 06 '25 08:12

Billy Goswell


1 Answers

You get a immutable dictionary back. You do not need to "capsulate" it in another dictionary. If you want to make it mutable write:

NSMutableDictionary* animals = [[defaults objectForKey:@"animals"] mutableCopy];

The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. If you want to store any other type of object, you should typically archive it to create an instance of NSData.

Values returned from NSUserDefaults are immutable, even if you set a mutable object as the value. For example, if you set a mutable string as the value for "MyStringDefault", the string you later retrieve using stringForKey: will be immutable.

Note: The user defaults system, which you programmatically access through the NSUserDefaults class, uses property lists to store objects representing user preferences. This limitation would seem to exclude many kinds of objects, such as NSColor and NSFont objects, from the user default system. But if objects conform to the NSCoding protocol they can be archived to NSData objects, which are property list–compatible objects. For information on how to do this, see ““Storing NSColor in User Defaults”“; although this article focuses on NSColor objects, the procedure can be applied to any object that can be archived.

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsuserdefaults_Class/Reference/Reference.html

like image 119
LuckyLuke Avatar answered Dec 08 '25 21:12

LuckyLuke