NSUserDefaults vs SQLite3. NSUSerDefaults immutable?
Pardon this, I know there's are answers out there for these question already. But I would like to know whether is my approach of choosing NSUserDefaults for my implementation correct.
I am trying to do a 'favourite list' to be displayed on UITableView
where开发者_JAVA技巧 I will need to save about 5 objects for each list. So I figured I will have NSDictionary
within a NSArray
for my tableView dataSource.
I was taken aback from using NSUserDefaults
when I read "Values returned from NSUserDefaults are immutable". Is there a way I can manipulate the objects stored? For example, read the array from NSUSerDefaults
then add new objects onto it and store it back.
NSUserDefaults
looks very easy to use.
EDIT Can we insert mutable objects in?
You can read object from NSUserDefaults like this:
//Read from NSUSerDefaults
NSMutableArray* favListArray = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"listArray"]];
//Add objects to array
[favListArray addObject:@"NewObject1"];
[favListArray addObject:@"NewObject2"];
//Overwrite the NSUSerDefaults valueForKey:@"listArray"
[[NSUserDefaults standardUserDefaults] setObject:favListArray forKey:@"listArray"];
[[NSUserDefaults standardUserDefaults] synchronize];
You can call mutableCopy
to get a copy of of an object if it is part of a Mutable/Immutable cluster such as NSArray/NSMutableArray NSDictionary/NSImmutableDictionary, etc.
So get the object out of the dictionary - call mutableCopy on it and you can modify it and save it back.
Remember that this method has a copy in its name, so you need to release the copy when you are finished with it.
精彩评论