将值连接到NSMutableDictionary中的相同键

时间:2016-10-05 10:46:34

标签: ios objective-c cocoa-touch

我从数据库中获取数据,并使用while循环检索数据。

success = [db executeQuery:@"SELECT * FROM apidataTwo;"];

while([success next]){

    int first = [success intForColumn:@"id"];
    NSString *id = [NSString stringWithFormat:@"%d",first];
    [_tempArray addObject:id];

    NSString *country_name = [success stringForColumn:@"country_name"];
    [_tempArray addObject:country_name];

    NSString *breezometer_description = [success stringForColumn:@"breezometer_description"];
    [_tempArray addObject:breezometer_description];

    NSString *country_description = [success stringForColumn:@"country_description"];
    [_tempArray addObject:country_description];

    NSString *dateString= [success stringForColumn:@"dateString"];
    [_dateSectionArray addObject:dateString];

    [_dataDictionary setObject:_tempArray forKey:dateString];

}

假设我们在循环的不同迭代中获得相同的密钥。当我将数组传递给NSMutableDictionary时,之前的值将被替换并丢失。

如果我不断更新NSMutableArray,那么之前密钥的值也会添加到其他密钥中。

所以在这种情况下,当我们想要将值连接到同一个键时,那么我们的方法应该是什么。

字典应如下所示:

{
  2016-10-05" =     (
      5,
      "United States",
      "Fair Air Quality",
      "Good air quality"
  );
  "2016-10-06" =     (
      5,
      "United States",
      "Fair Air Quality",
      "Good air quality"
  );
}

1 个答案:

答案 0 :(得分:1)

一旦找到了这批数据的密钥,请尝试从字典中检索该密钥的对象。如果objectForKey:返回nil,则创建一个新的可变数组。然后将该数组设置为该键的字典对象。

然后将每批新数据添加到数组中,而不是添加到字典中。这是结构草图:

while( /* processing data */){

    // Collect this batch
    NSArray * entry = ...;
    // Figure out the dictionary key for the batch.
    // (it doesn't have to be a string, this is just for example)
    NSString * key = ...;

    // Try to retrieve the object for that key
    NSMutableArray * entries = _dataDictionary[key];

    // If the result is `nil`, the key is not in the dictionary yet.
    if( !entries ){

        // Create a new mutable array
        entries = [NSMutableArray array];
        // Add that to the dictionary as the value for the given key
        _dataDictionary[key] = entries;
    }

    // Now `entries` is a valid `NSMutableArray`, whether it already
    // existed or was just created. Add this batch.
    [entries addObject:entry];

    // Move on to the next batch.
}