Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving NSDictionary to NSUserDefaults

I have a NSMutableDictionary, and i have added values to it (several key pair values). Now i require to save this NSMutableDictionary to a NSUserDefaults object.

1.) My code as follows; I am not sure if it is correct , and also i need to know how to retrieve the NSMutableDictionary from the NSUSerDefault ?

2.) After retrieving the NSMutableDictionary i need to save it to a NSDictionary. How could i do these ?

NSMutableDictionary *dic = [[NSMutableDictionary  alloc] init];  [dic addObject:@"sss" forKey:@"hi"]; [dic addObject:@"eee" forKey:@"hr"];   [NSUserDefaults standardDefaults] setObject:dic forKey:@"DicKey"];  [[NSUserDefaults standardDefaults] synchronize]; 
like image 915
shajem Avatar asked Mar 30 '12 16:03

shajem


People also ask

Is NSUserDefaults thread-safe?

Thread SafetyThe UserDefaults class is thread-safe.

What is NSUserDefaults in Swift?

A property list, or NSUserDefaults can store any type of object that can be converted to an NSData object. It would require any custom class to implement that capability, but if it does, that can be stored as an NSData. These are the only types that can be stored directly.


1 Answers

Your code is correct, but the one thing you have to keep in mind is that NSUserDefaults doesn't distinguish between mutable and immutable objects, so when you get it back it'll be immutable:

NSDictionary *retrievedDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"DicKey"]; 

If you want a mutable dictionary, just use mutableCopy:

NSMutableDictionary *mutableRetrievedDictionary = [[[NSUserDefaults standardUserDefaults] objectForKey:@"DicKey"] mutableCopy]; 
like image 132
yuji Avatar answered Sep 23 '22 01:09

yuji