从NSUserDefaults设置/访问多维数组

时间:2012-05-22 17:29:28

标签: iphone objective-c ipad multidimensional-array nsuserdefaults

我在从NSUserDefault存储和访问多维数组时遇到了一些麻烦。任何帮助,将不胜感激。我运行此代码时得到的错误是“ * 因未捕获的异常而终止应用程序'NSInternalInconsistencyException',原因:' - [__ NSCFArray insertObject:atIndex:]:mutating方法发送到不可变对象'”< / p>

//To create, add values to and store arrays
multiArray = [[NSArray alloc] init];
multiArray = [NSArray arrayWithObjects:[NSMutableArray array], [NSMutableArray array], [NSMutableArray array], nil];

[[multiArray objectAtIndex:0] addObject:[NSNumber numberWithDouble:number1]];
[[multiArray objectAtIndex:1] addObject:[NSNumber numberWithDouble:number2]];
[[multiArray objectAtIndex:2] addObject:[NSNumber numberWithDouble:number3]];
NSUserDefaults * standardUserDefaults = [NSUserDefaults standardUserDefaults]
[standardUserDefaults setObject:multiArray forKey:@"multiArray"];
[standardUserDefaults synchronize];

//To access the array
NSArray *multiArrayCopy = [[NSArray alloc] init];
multiArrayCopy = [[standardUserDefaults objectForKey:@"multiArray"] mutableCopy];
NSLog(@"array count is %i", [[multiArrayCopy objectAtIndex:2] count]);
Label1.text = [NSString stringWithFormat:@"%@", [[multiArrayCopy objectAtIndex:0] objectAtIndex:0]];
Label2.text = [NSString stringWithFormat:@"%@", [[multiArrayCopy objectAtIndex:1] objectAtIndex:0]];
Label3.text = [NSString stringWithFormat:@"%@", [[multiArrayCopy objectAtIndex:2] objectAtIndex:0]];

1 个答案:

答案 0 :(得分:0)

您收到错误,因为[NSMutableArray array]是NSArray的类方法,它返回一个空(不可变)数组。请记住,NSMutableArray是NSArray的子​​类。尝试创建NSMutableArray列表,因此:

NSMutableArray *mutableArray0 = [[NSMutableArray alloc] init];
NSMutableArray *mutableArray1 = [[NSMutableArray alloc] init];
NSMutableArray *mutableArray2 = [[NSMutableArray alloc] init];

multiArray = [[NSMutableArray alloc] init];
multiArray = [NSMutableArray arrayWithObjects:mutableArray0, mutableArray1, mutableArray2, nil];

另外,我认为multiArray也应该是NSMutableArray。试试这个以查看错误是否消失。

如果它不起作用,请尝试将逻辑拆分为最简单的元素。你可以用你的对象保存并获取单维数组吗?也就是说,如果您执行以下操作会发生什么?

NSMutableArray *mutableArray0 = [[NSMutableArray alloc] init];
[mutableArray0 addObject:[NSNumber numberWithInt:myNumber]];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:mutableArray0 forKey:@"myMutableArray"];
[[NSUserDefaults standardUserDefaults] synchronize];    

当你开始工作时,请尝试将其嵌套到另一个可变数组中,因此:

NSMutableArray *mutableArray0 = [[NSMutableArray alloc] init];
[mutableArray0 addObject:[NSNumber numberWithInt:myNumber]];

NSMutableArray *multiArray = [[NSMutableArray alloc] init];
[multiArray addObject:mutableArray0]; 
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:multiArray forKey:@"myMutableArray"];
[[NSUserDefaults standardUserDefaults] synchronize];    

这应该有用。