0

我被难住了。我只是想将填充了 NSNumbers 或 NSStrings 的 NSArray 保存到 NSUserDefaults。奇怪的是,如果我在阅读之前保存它,它会起作用 - 但如果我不保存并阅读它(在之前的发布中保存之后)它是零。就像每次我在 XCode 中点击 Run (Command-R) 时,默认值都会被清除。

NSArray *arrayToSave = [NSArray arrayWithObjects: [NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3], nil];
[[NSUserDefaults standardUserDefaults] setObject:arrayToSave forKey:@"TestKey"];  //if I comment this line arrayRead will be nil even after I had saved it with this line on a prior run

阅读:

NSArray *arrayRead = [[NSUserDefaults standardUserDefaults] objectForKey: @"TestKey"];
NSLog(@"arrayRead: %@", arrayRead);
4

2 回答 2

2

您应该synchronize在写入用户默认值后调用:

// Write
NSArray *arrayToSave = [NSArray arrayWithObjects: [NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3], nil];
[[NSUserDefaults standardUserDefaults] setObject:arrayToSave forKey:@"TestKey"];
[[NSUserDefaults standardUserDefaults] synchronize];

// Read
NSArray *arrayRead = [[NSUserDefaults standardUserDefaults] objectForKey:@"TestKey"]; // or arrayForKey
NSLog(@"arrayRead: %@", arrayRead);
于 2012-05-01T09:49:08.397 回答
0

尝试以下操作:

节省:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
NSMutableArray *arr = ... ; // set value 
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arr]; 
[defaults setObject:data forKey:@"TestKey"]; 

加载:

 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
    NSData *data = [defaults objectForKey:@"TestKey"]; 
    NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithData:data]; 
于 2012-05-01T09:40:16.267 回答