Correct way to use NSUserDefaults?

I have a problem that I can’t lower my head, and I hope someone can give me a hint or help.

I have a table containing 7 objects. When clicking one of the objects, the user is presented with a new table corresponding to the pressed objects. Inside this table, the user can click the "Add" button, transferring them to a new table, where they can select objects for table 2.

Table 1 and table 3 (first and last) do not need to be edited, but table 2 is necessary. I need to add the data that the user selects from table 3, and save it when entering the application again after it is closed.

There are always 7 objects in table 1. And you need to have another table 2. Therefore, I'm not sure the best way is to create 7 different arrays.

I have looked and used NSUserDefaultsbefore, however I'm not sure what a good way to get closer to this when using NSUserDefaults.

+3
source share
1 answer

you need your array from userdefaults to change it, rewrite it back to userdefaults. Getting an array:

NSMutableArray *yourArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"yourKey"]mutableCopy];

Array setup:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:yourArray forKey:@"yourKey"];
[userDefaults synchronize];

Or use dictionaries and paste them

NSMutableDictionary *yourDict1 = [[NSUserDefaults standardUserDefaults]objectForKey:@"yourKey1"]mutableCopy];
NSMutableDictionary *yourDict2 = [[yourDict1 valueForKey:@"yourKey2"]mutableCopy];

    // THIS WILL ADD DATA TO YOUR DICTIONARY
[yourDict2 setValue:@"value" forKey:@"key"];

    // THIS WILL GET DATA FROM YOUR DICTIONARY
NSString *tempStr = [yourDict2 valueForKey:@"keyToGet"];

    // This will write your sub dictionary to your main dictionary
[yourDict1 setObject: yourDict2 forKey:@"yourKey2"];

    // This will write your main dictionary back out to user defaults
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject: yourDict1 forKey:@"yourKey1"];
[userDefaults synchronize];
[yourDict1 release];
[yourDict2 release];
+6
source

All Articles