ios - 复制 NSUserDefaults 数组并编辑数组
问题描述
当我替换 NSMutableArray 中的值并且消息是
“由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'”
我正在做的是首先存储一个数组NSUserDefaults
,然后获取数组。之后,我正在编辑该数组的副本。
NSMutableArray *getArr = [[NSUserDefaults standardUserDefaults] valueForKey:@"List"];
NSMutableArray *newArray = [[NSMutableArray alloc]initWithArray:getArr copyItems:YES];
现在我正在替换特定索引处的新数组的值
for(int i = 0;i<newArray.count;i++)
{
NSDictionary *dict = [newArray objectAtIndex:i];
dict["key"] = "NewValue"
[newArray replaceObjectAtIndex:i withObject:d];
}
解决方案
问题是存储的字典对象是不可变的,所以你需要init
一个带有它的内容的可变对象,做这个工作然后再次保存它看这个例子
NSMutableArray*old= [NSMutableArray new];
[old addObject:@{@"key":@"value"}];
[[NSUserDefaults standardUserDefaults] setObject:old forKey:@"www"];
NSMutableArray*edited = [[[NSUserDefaults standardUserDefaults] objectForKey:@"www"] mutableCopy];
NSMutableDictionary*dic = [[NSMutableDictionary alloc] initWithDictionary:[edited objectAtIndex:0]];
dic[@"key"] = @"value2";
[edited replaceObjectAtIndex:0 withObject:dic];
[[NSUserDefaults standardUserDefaults] setObject:edited forKey:@"www"];
NSMutableArray*vvv = [[NSUserDefaults standardUserDefaults] objectForKey:@"www"];
NSLog(@"%@",vvv); /// key:value2
推荐阅读
- spring-boot - 获取 java.nio.file.NoSuchFileException: ....\asm-all-repackaged.jar
- c++ - 解锁被另一个线程锁定的互斥锁
- php - 未找到 DocuSign PHP 快速入门代码类“DocuSign\eSign\ApiClient”
- c# - 如何在 xamarin iOS 中的 UiKit 中获取一个简单的初始边框
- java - Android 套接字安全异常
- swiftui - 如何在 SwiftUI 中设置 SF Symbol 的大小?
- android - 如果找不到对象,为什么流动不返回任何数据
- amazon-web-services - 经过身份验证的登录后出现 AWS Cognito NotAuthorizedException“无效访问令牌”错误
- javascript - 如何在 react-native 中控制打开/关闭模式
- javascript - Firebase on change 事件。如何知道谁更改了数据?