使用NSNumbers保存纯NSArray

时间:2012-05-01 09:30:53

标签: ios nsarray nsuserdefaults

我在这里难过。我只是想在NSUserDefaults中保存一个装有NSNumbers或NSStrings的NSArray。奇怪的是,如果我在阅读它之前保存它是有效的 - 但是如果我不保存并阅读它(在之前的启动中保存之后)它就是零。这就像每次在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);

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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];