开发者

The proper way to use NSUserDefaults?

I have a 开发者_Go百科problem that I can't get my head around, and am hoping someone could give me a hint or help.

I have a table, which contains 7 objects. When pressing one of the object the user is presented with a new table, corresponding to the pressed objects. Inside this table the user is able to press an 'Add' button, taking them to a new table where they can choose the objects for table 2.

Table 1 and table 3 (the first and the last) do not need to be edited in, however table 2 needs to. I need to add the data the user pick from table 3 and save it when entering the app again after it has been closed.

In table 1 there is always 7 objects. And needs to be able to have a different table 2. So I am not sure if the best way is to create 7 different arrays.

I have looked, and have been using, NSUserDefaults before, however i am not sure what a good way to approach this is, when using NSUserDefaults.


you need to get your array out of the userdefaults modify it then rewrite it back into the userdefaults. Getting array:

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

Setting array:

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

Or use dictionaries and nest 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];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜