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

这保证了可变副本.

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...