ios – 向检索到的NSMutableArray添加新对象 – 返回NSInternalInconsistencyException

ios – 向检索到的NSMutableArray添加新对象 – 返回NSInternalInconsistencyException,第1张

概述当我尝试将对象添加检索到的NSMutableArray时,我不断收到此错误. Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable o 当我尝试将对象添加到检索到的NSMutableArray时,我不断收到此错误.

Terminating app due to uncaught exception 'NSInternalinconsistencyException',reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'

检索:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];    NSMutableArray *arrayOfTitles = [userDefaults objectForKey:@"mainArraySaveData"];    NSMutableArray *arrayOfSubjects = [userDefaults objectForKey:@"subjectArraySaveData"];    NSMutableArray *arrayOfDates = [userDefaults objectForKey:@"dateArraySaveData"];    _mutableArray=arrayOfTitles;    _subjectArray=arrayOfSubjects;    _dateArray=arrayOfDates;    [_tableVIEw reloadData];

保存:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];_mutableArray = [[NSMutableArray alloc] initWithArray:[userDefaults objectForKey:@"mainArraySaveData"]];[userDefaults setobject:_mutableArray forKey:@"mainArraySaveData"];[userDefaults synchronize];_dateArray = [[NSMutableArray alloc] initWithArray: [userDefaults objectForKey:@"dateArraySaveData"]];[userDefaults setobject:_dateArray forKey:@"dateArraySaveData"];[userDefaults synchronize];_subjectArray = [[NSMutableArray alloc] initWithArray: [userDefaults objectForKey:@"subjectArraySaveData"]];[userDefaults setobject:_subjectArray forKey:@"subjectArraySaveData"];[userDefaults synchronize];

我很困惑,因为我认为这是为了返回一个NSMutableArray,但它没有 – NSArray.我的问题是什么?
谢谢,SebOH

解决方法

I’m confused as I thought this was designed to return an NSMutableArray,but it says not – NSArray. What’s my issue?

NSUserDefaults的文档在objectForKey:方法的“特殊注意事项”部分中专门讨论了这个问题:

Special ConsIDerations

The returned object is immutable,even if the value you originally set was mutable.

修复这个问题很简单 – 使用mutablecopy:,initWithArray:或arrayWithArray:方法制作可变副本:

_mutableArray=[arrayOfTitles mutablecopy];                      // You can do this..._subjectArray=[NSMutableArray arrayWithArray:arrayOfSubjects];  // ...or this_dateArray=[[NSMutableArray alloc] initWithArray:arrayOfDates]; // ...or this.
总结

以上是内存溢出为你收集整理的ios – 向检索到的NSMutableArray添加新对象 – 返回NSInternalInconsistencyException全部内容,希望文章能够帮你解决ios – 向检索到的NSMutableArray添加新对象 – 返回NSInternalInconsistencyException所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1071919.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存