gpt4 book ai didi

ios - 从 plist 读取的空 NSMutableArray 变成不可变对象(immutable对象)

转载 作者:行者123 更新时间:2023-11-28 19:05:15 25 4
gpt4 key购买 nike

将一个空的 NSMutableArray 写入磁盘,然后读回它,它就变成了一个不可变对象(immutable对象)。
但是,如果 NSMutableArray 不为空,则不会。怎么解释?
这是代码:

NSMutableArray *testItems1 = [NSMutableArray array];
NSMutableDictionary *testList1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:testItems1, @"list_items", @"list1", @"list_name", nil];

NSMutableArray *testItems2 = [NSMutableArray arrayWithObjects:@"item11", @"item22", nil];
NSMutableDictionary *testList2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:testItems2, @"list_items", @"list2", @"list_name", nil];

NSMutableArray *testLists = [NSMutableArray arrayWithObjects:testList1, testList2, nil];

[testLists writeToFile:@"/tmp/testLists" atomically:YES];

NSMutableArray *testReadLists = [NSMutableArray array];
[testReadLists setArray:[NSArray arrayWithContentsOfFile:@"/tmp/testLists"]];
NSMutableDictionary *testReadList = [testReadLists objectAtIndex:0];
NSMutableArray *testReadItems = [testReadList objectForKey:@"list_items"];
[testReadItems addObject:@"item3"]; // Crashes here: "*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray insertObject:atIndex:]: mutating method sent to immutable object'"

最佳答案

这两行代码:

NSMutableArray *testReadLists = [NSMutableArray array];
[testReadLists setArray:[NSArray arrayWithContentsOfFile:@"/tmp/testLists"]];

给你一个不可变对象(immutable对象)的可变数组。您可以在 testReadLists 中添加和删除对象,但您从该数组(最初从 plist 加载)获得的所有内容都是不可变的。

更新 - 我正要发布有关解决方案的信息,但 Vivek 的回答描述了我要说的内容。

关于ios - 从 plist 读取的空 NSMutableArray 变成不可变对象(immutable对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21031412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com