2

I use the NSUserDefaults method to save data. I save an int and an NSMutableArray.

The int gets saved properly when the app terminates, enters the background, or switches to another view. The array saves when the app enters the background and when it switches to another view, but doesn't save every time I exit the simulator and come back in, even though I use the exact same code for the int and the NSMutableArray.

Here's my code for defining the NSMutableArray:

array = [[NSMutableArray alloc] init];
if ([prefs objectForKey:@"array"] != nil) {
array = [prefs objectForKey:@"array"];
}

And then for editing and saving it:

[array addObject:anObject];
[prefs setObject:array forKey:@"array"];
[prefs synchronize];

The int has the exact same code except for the changes between array and int parts.

Can anyone tell me what's wrong? I've checked many related questions but none of them solved my problem.

Thanks in advance.

4

4 回答 4

6

"Values returned from NSUserDefaults are immutable, even if you set a mutable object as the value."

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html

You're assigning a pointer to an immutable NSArray returned by [NSUserDefaults objectForKey:...] to a pointer to an NSMutableArray. You then use addObject: on the NSArray (which has no effect) and save the unchanged NSArray.

(You may also have a memory leak since you're allocing the NSImmutableArray every time.)

于 2011-11-20T17:32:05.410 回答
2

Use this code.

This will definitely save & retrieve your NSUserDefault values.

- (void) retrieveMyState
 {
//Retrieving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

NSInteger *yourIntValue = [prefs integerForKey:@"yourIntValue"];

    // convert your NSData to array, and then use it as required.   

NSData *dataRepresentingSavedArray = [prefs objectForKey:@"yourArray"];
if (dataRepresentingSavedArray != nil)
{
    NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
    if (oldSavedArray != nil)
        yourArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];
    else
        yourArray = [[NSMutableArray alloc] init];
}

}


 -(void) saveMyState 
{
//saving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

[prefs setInteger:yourIntValue forKey:@"yourIntValue"];

    // convert your array to NSData & then save it as object.

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:yourArray];
[prefs setObject:data forKey:@"yourArray"];

[prefs synchronize];
 }
于 2011-11-17T09:55:33.527 回答
0

写 :

NSMutableArray* array = [NSMutableArray array];
if ([prefs objectForKey:@"array"] != nil)
    [array setArray:[prefs objectForKey:@"array"]];

在定义 NSMutableArray 时。

于 2011-11-16T15:16:11.453 回答
0

你不能保存一个“int”。它不是一个 NSObject。

但是您可以将 NSNumber 嵌入到您的数组中,这样可以保存。

尝试[NSNumber numberWithInt: ](我链接到 Apple 文档)。

希望这可以解决问题。

于 2011-11-16T15:17:40.380 回答