NSDictionary的深度可变副本到NSMutableDictionary中

时间:2012-02-25 19:23:52

标签: objective-c ios nsarray nsdictionary

我有一个属性列表,我读到了NSDictionary,我想从中创建一个可变副本到NSMutableDictionary来编辑内容,然后能够通过复制原始内容来重置可变字典。 / p>

NSDictionary *defaultRows;
NSMutableDictionary *rows;

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"];
defaultRows = [[[NSDictionary alloc] initWithContentsOfFile: plistPath] objectForKey:@"rows"];

这就是我尝试创建原始字典的副本(根据Apple's recommendation)

rows = [NSMutableDictionary dictionaryWithDictionary: defaultRows];

当我尝试使用:

更改字典行的内容时

[[[rows objectForKey:self.company.coaTypeCode] objectForKey:statementType] removeObjectsAtIndexes:rowsToDelete];

我收到运行时错误*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray removeObjectAtIndex:]: mutating method sent to immutable object'

我已阅读article here,但想知道是否有更优雅的方法来实现深层复制?

2 个答案:

答案 0 :(得分:8)

由于您从属性列表中加载defaultRows,最简单的方法是使用可变容器反序列化属性列表。

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"];
NSData *rowsData = [NSData dataWithContentsOfFile:plistPath];

NSMutableDictionary *rows = [NSPropertyListSerialization propertyListWithData:rowsData
    options:NSPropertyListMutableContainers format:NULL error:NULL];

答案 1 :(得分:1)

您考虑过使用

吗?
NSMutableDictionary *rows = [[[NSMutableDictionary alloc] initWithContentsOfFile:plistPath] objectForKey:@"rows"];