【发布时间】:2012-09-12 14:13:13
【问题描述】:
- (NSMutableDictionary *)updateTemplates:(NSMutableDictionary *)oldTemplates
forSpecType:(NSString *)specType {
// oldTemplates is an NSMutableDictionary pulled from a plist
// specType is used for flexible paths, to eliminate duplicate code
// Make a dict of the parameters object (about to be overwritten)
NSMutableDictionary *parameters = [oldTemplates valueForKeyPath:
[NSString stringWithFormat:@"root.%@.parameters", specType]];
// Dump the new data into the matching object
[oldTemplates setValue:[updateTemplates valueForKeyPath:
[NSString stringWithFormat:@"data.%@", specType]]
forKeyPath:[NSString stringWithFormat:@"root.%@", specType]];
// Put the parameters back, since they don't exist anymore
/* Instant crash, with the debugger claiming something is immutable
* But I just used the exact same method on the line above
* updateTemplates isn't immutable either; it's only when I try to mutate
oldTemplates after putting in updateTemplates -- and only the update
seems to be breaking things -- that I get the exception and crash
*/
[oldTemplates setValue:parameters forKeyPath:
[NSString stringWithFormat:@"root.%@.parameters", specType]];
return oldTemplates;
}
我可以设置一个循环来一次写入一个updateTemplates.specType 的对象,这样只有那些部分被替换,然后我不必对参数做任何事情,但如果它现在是不可变的,那将是什么时候我尝试再次写信给它。这对我没有任何好处。
【问题讨论】:
-
最好同时记录
oldTemplates和parameters以查看运行时认为它们是什么类型。 (错误是否给出了对象地址?如果是,它是否与您在此代码中使用的字典之一匹配?)
标签: objective-c xcode immutability nsmutabledictionary