在NSArray中更新NSDictionary

Abh*_*nav 2 cocoa-touch objective-c nsdictionary nsarray ios

我有一个NSArrayNSDictionaries.我需要更新NSArrayNSDictionaries与新值更新的字典重点之一的价值.

请参见下面的NSArray结构.Key3如果Key1匹配某个值(例如2),我想更新此结构内部的值.这样做最快的方法是什么?我不想使用传统的For循环.

[myArray valueForKeyPath:@"@unionOfObjects.Key3"];

<__NSCFArray 0xe70c10>(
{
    Key1 = 1;
    Key2 = "New Location";
    Key3 =     (
        Data1,
        Data2,
        Data3
    );
},
{
    Key1 = 2;
    Key2 = "Old Location";
    Key3 =     (
        Data1,
        Data2,
        Data4
    );
}
)
Run Code Online (Sandbox Code Playgroud)

san*_*thu 5

我们可以使用谓词来解决它:

NSArray *dictionaryArray;
NSNumber *key =@2;
NSPredicate *predicate =[NSPredicate predicateWithFormat:@"Key1=%@",key];
NSArray *result =[dictionaryArray filteredArrayUsingPredicate:predicate];
Run Code Online (Sandbox Code Playgroud)

结果数组现在有所有字典(key1 = 2)

Dictionarys不能直接编辑,它们必须是NSMutableDictionary才能编辑.假设它们是NSMutableDictionary实例:

NSMutableDictionary *dic =result[0];
[dic setObject:someObject forKey:@"key3"];
Run Code Online (Sandbox Code Playgroud)