0

I have one NSArray with NSMutableDictionaries .Example testArray =[dict1,dict2,dict3,dict4]. Each dictionary in the array is something like

dict1=  {
    country = "INDIA";
    flag = "A";
    Currency = "Rupees";
    rate = 10;
}

The all values are changeable. Sometimes

dict1 = {
    country = "USA";
    flag = "SA";
    Currency = "Dollar";
    rate = 50;
   }

I need to update the value of the key rate of all dictionaries in the testArray if country = "INDIA" and flag = "A" and Currency = "Rupees" and Do not need to change the value of the rate key all other dictionaries in side the testArray.

Darshan Kunjadiya
  • 3,323
  • 1
  • 29
  • 31
user3762713
  • 101
  • 3
  • 13

3 Answers3

3

Just try the below.

for(NSMutableDictionary *dic in array)
{
    if([[dic valueForKey:@"country"] isEqualToString:@"INDIA"] &&
       [[dic valueForKey:@"flag"] isEqualToString:@"A"] &&
       [[dic valueForKey:@"Currency"] isEqualToString:@"Rupees"])
    {
        [dic setValue:@"100" forKey:@"rate"];
    }
}
Ryan
  • 4,799
  • 1
  • 29
  • 56
0

Here is a complete example what you need

NSDictionary *dict1 =  @{
                             @"country" : @"INDIA",
                             @"flag" : @"A",
                             @"Currency" : @"Rupees",
                             @"rate" : @10
                             };
    NSDictionary *dict2 = @{
                            @"country" : @"USA",
                            @"flag" : @"SA",
                            @"Currency" : @"Dollar",
                            @"rate" : @50
                            };
    NSArray *testArray = @[dict1, dict2];
    NSMutableArray *testMutableArray = [testArray mutableCopy];
    for (int i = 0; i < testMutableArray.count; i++) {
        NSDictionary *country = testMutableArray[i];
        if ([country[@"country"] isEqualToString:@"INDIA"] &&
            [country[@"flag"] isEqualToString:@"A"] &&
            [country[@"Currency"] isEqualToString:@"Rupees"])
        {
            NSMutableDictionary *countryMutable = [country mutableCopy];
            countryMutable[@"rate"] = @100;
            testMutableArray[i] = [countryMutable copy];
        }
    }
    testArray = [testMutableArray copy];
l0gg3r
  • 8,864
  • 3
  • 26
  • 46
0

Use NSMutableArray instead of NSArray.

then,

NSDictionary *dict = [testArray objectAtIndex:0];

dict[@"rate"] = @"11";

[testArray replaceObjectAtIndex:0 withObject:dict];

Hope this will help you.