Abhinav
Abhinav

Reputation: 38162

Updating NSDictionary inside an NSArray

I have a NSArray of NSDictionaries. I need the updated NSArray of NSDictionaries with value of one of the dictionary key updated with new value.

Please see below the NSArray structure. I want to update the value for Key3 inside this structure if Key1 matches with some value (e.g. 2). What would the fastest way of doing this. I do not want to use traditional For loop.

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

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

Upvotes: 2

Views: 2506

Answers (3)

Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 21966

Let's suppose that you already have an array containing all mutable dictionaries. The first step is to get what dictionaries you need to change:

NSPredicate* predicate= [NSPredicate predicateWithFormat: @"Key1=2"];
NSArray* filteredArray= [myArray filteredArrayUsingPredicate: predicate];

The second step is to replace the Key3 value for each object in the array. If you execute a selector on an array, and NSArray doesn't respond to that selector, the selector is performed on it's objects:

[filteredArray performSelector: @selector(setValue:forKey:) withObject: someValue withObject: @"Key3"];

After this statement you don't need to replace any object in myArray, because the filtered array contains the same objects that are in myArray, which are mutable dictionaries.

Upvotes: 1

Garoal
Garoal

Reputation: 2374

I would also go for predicates as @santhu stated on his answer. However, I want to point that when searching an unsorted array linear search (that is, looping through every object and checking if it's the wanted one) is optimal. Probably predicates will provide an speed-up due to their internal routines, but a predicate will still execute the "traditional for loop" you want to avoid and thus the speed-up will not be very significant.

There are other searching algorithms which provide a significant speed-up, but they are only valid for sorted databases (unless you have a quantum iPhone ;) ).

If you are interested on this topic, here you can find some types of search algorithms with an analysis of their complexity.

Upvotes: 0

santhu
santhu

Reputation: 4792

We can solve it by using predicates:

NSArray *dictionaryArray;
NSNumber *key =@2;
NSPredicate *predicate =[NSPredicate predicateWithFormat:@"Key1=%@",key];
NSArray *result =[dictionaryArray filteredArrayUsingPredicate:predicate];

result array now has all dictionaries having (key1 = 2)

Dictionarys can't be edited directly, they must be NSMutableDictionary to edit. Assuming they are NSMutableDictionary instances:

NSMutableDictionary *dic =result[0];
[dic setObject:someObject forKey:@"key3"];

Upvotes: 5

Related Questions