开发者

NSUserDefaults vs SQLite3. NSUSerDefaults immutable?

开发者 https://www.devze.com 2023-04-04 00:02 出处:网络
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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号