ios – 发送到不可变对象的变异方法 – 错误

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

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


[defaultdefects setobject:loaddefects forKey:@"defaultdefects"];
NSLog(@"%f %f",self.defectPositionY);

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


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

[self presentViewController:secondViewController animated:YES completion:nil];
NSLog(@"%f %f",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类型的未捕获异常终止

我很困惑我如何将它作为一个可变阵列,但它称之为Immutable意味着我不能改变它..这是我第一次遇到这个错误而且我正在努力抓住它.

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

解决方法

分配给NSMutableArray的问题是,只有在为defaultdefects分配了给定键的NSMutableArray时,它才有效.

注意:NSUserDefaults始终返回不可变对象.

这样做

NSMutableArray *loaddefects = [[defaultdefects objectForKey:@"defaultdefects"]mutablecopy];

这保证了可变副本.

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...