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;
}

一度に1つのオブジェクトを書き込むループを設定して、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であるキーと値のペアを含む場合、は、それらの不変のインスタンスを値として含む可変ディクショナリを返します。NSDictionarymutableCopyNSDictionary

ディープコピーを実行するか、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 に答える