mutating方法发送到不可变对象 - 错误

时间:2014-04-21 16:10:45

标签: ios objective-c

NSUserDefaults *defaultDefects = [NSUserDefaults standardUserDefaults];
    NSLog(@"%f %f", self.defectPositionX, self.defectPositionY);

NSMutableArray *loadDefects = [defaultDefects objectForKey:@"defaultDefects"];
    NSLog(@"%f %f", self.defectPositionX, self.defectPositionY);
if (loadDefects == nil) {
    loadDefects = [NSMutableArray array];
}
    NSLog(@"%f %f", self.defectPositionX, self.defectPositionY);
//PROBLEM HERE
[loadDefects addObject:[NSNumber numberWithDouble:self.defectPositionX ]];
[loadDefects addObject:[NSNumber numberWithDouble:self.defectPositionY ]];
NSLog(@"%f %f", self.defectPositionX, self.defectPositionY);


[defaultDefects setObject:loadDefects forKey:@"defaultDefects"];
NSLog(@"%f %f", self.defectPositionX, self.defectPositionY);

[defaultDefects synchronize];
NSLog(@"%f %f", self.defectPositionX, self.defectPositionY);


ViewControllerImage *secondViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"ViewControllerImage"];
secondViewController.thicknessValue1 = self.thicknessValue1;
secondViewController.capWidthValue1 = self.capWidthValue1;
NSLog(@"%f %f", self.defectPositionX, self.defectPositionY);

[self presentViewController:secondViewController animated:YES completion:nil];
NSLog(@"%f %f", self.defectPositionX, self.defectPositionY);

记录此

2014-04-21 17:03:02.838 U[8958:60b] 169.728546 274.674475
2014-04-21 17:03:02.840 U[8958:60b] 169.728546 274.674475
2014-04-21 17:03:02.842 U[8958:60b] 169.728546 274.674475

完整的错误报告就是这个

*由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:' - [__ NSCFArray insertObject:atIndex:]:发送到immutable对象的mutating方法' * 第一次抛出调用堆栈: (0x2e8e2f03 0x39077ce7 0x2e8e2e45 0x2e85642b 0xb93d3 0x311476c7 0x31147663 0x31147633 0x31132d7b 0x3114fa3d 0x31146c7d 0x31141ca7 0x31116e75 0x31115541 0x2e8adfe7 0x2e8ad4af 0x2e8abc9f 0x2e8167a9 0x2e81658b 0x337836d3 0x31175891 0xb7851 0x39575ab7) libc ++ abi.dylib:以NSException类型的未捕获异常终止

我对如何将它作为一个Mutable数组感到困惑但是它称之为Immutable意味着我无法改变它..这是我第一次遇到这个错误并且我很难掌握它。

当运行应用程序并将数据保存到可变数组中时,有时它会起作用,然后有时会崩溃......?

1 个答案:

答案 0 :(得分:29)

分配给NSMutableArray的问题是,只有在为defaultDefects分配给定键的NSMutableArray时才会有效。

注意:NSUserDefaults始终返回一个不可变对象。

改为

NSMutableArray *loadDefects = [[defaultDefects objectForKey:@"defaultDefects"]mutableCopy];

这保证了可变副本。