【问题标题】:How to replace the value of the key in NSMutableDictionary based on the another key value pair如何根据另一个键值对替换 NSMutableDictionary 中键的值
【发布时间】:2014-07-07 07:14:50
【问题描述】:

我有一个NSArrayNSMutableDictionaries。例如testArray =[dict1,dict2,dict3,dict4]. 数组中的每个字典都类似于

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

所有值都是可变的。有时

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

如果country = "INDIA"flag = "A"Currency = "Rupees",我需要更新testArray中所有字典的key rate的值,并且不需要更改testArray中所有其他字典的rate key的值.

【问题讨论】:

标签: ios iphone objective-c ipad nsdictionary


【解决方案1】:

试试下面的。

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

【讨论】:

    【解决方案2】:

    这是您需要的完整示例

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

    【讨论】:

      【解决方案3】:

      使用 NSMutableArray 代替 NSArray。

      那么,

      NSDictionary *dict = [testArray objectAtIndex:0];
      
      dict[@"rate"] = @"11";
      
      [testArray replaceObjectAtIndex:0 withObject:dict];
      

      希望这会对你有所帮助。

      【讨论】:

      • 嘿,看来你是个巫师,你正在变异一个不可变的对象。
      猜你喜欢
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 2012-06-07
      相关资源
      最近更新 更多