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

9
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:] :发送到不可变对象的可变方法' * 首次抛出调用堆栈: (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 类型终止并引发未捕获的异常

我很困惑为什么它被设置为可变数组,但是却称其为不可变数组,这意味着我无法进行更改。这是我第一次遇到这个错误,而且我很难理解。

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

1个回答

34

给NSMutableArray赋值的问题在于,只有在为给定的键分配了NSMutableArray时它才起作用。

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

请改用以下方法

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

这确保了可变的副本。


3
NSUserDefaults always 返回不可变对象,即使一个可变对象被归档。 - LombaX
收到。谢谢 @LombaX - lead_the_zeppelin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接