1
- (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这样只有那些部分被替换,然后我不必对参数做任何事情,但如果它现在是不可变的,那将是我尝试写入它的时候再次。那对我没有任何好处。

4

3 回答 3

4

如果我没记错的话,从 plist 或 NSUserDefaults 创建的字典默认是不可变的。您必须手动创建一个可变副本:

NSMutableDictionary *parameters = [[oldTemplates valueForKeyPath:
           [NSString stringWithFormat:@"root.%@.parameters", specType]] mutableCopy];
于 2012-09-12T14:41:00.113 回答
3

mutableCopy制作浅可变副本,而不是深可变副本。如果您有一个NSDictionary包含键/值对,其中值是NSDictionary实例,mutableCopy则将返回一个可变字典,其中包含这些NSDictionary不可变实例作为值。

您要么需要进行深层复制,要么使用 plist 序列化功能在启用可变集合选项的情况下解码 plist。或者你可以从旧的集合中创建一个新的集合。

于 2012-09-12T14:54:21.080 回答
0

你可以简单地做:

NSMutableDictionary* oldTemplates = [NSMutableDictionary dictionaryWithDictionary:[oldTemplates valueForKeyPath:
                  [NSString stringWithFormat:@"root.%@.parameters", specType]]];

这将从现有的 NSDictionary 创建一个可变副本

于 2012-09-12T14:58:29.293 回答