1

我在存储和访问 NSUserDefault 中的多维数组时遇到了一些麻烦。任何帮助,将不胜感激。运行此代码时出现的错误是“ *由于未捕获的异常 'NSInternalInconsistencyException' 而终止应用程序,原因:'-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'”

//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]];
4

1 回答 1

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];    

这应该有效。

于 2012-05-22T19:36:46.447 回答