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

前端之家收集整理的这篇文章主要介绍了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相关文章