我需要一个NSMutableDictionary,其值将是数组,将在应用程序运行时创建,并在以后填充

时间:2014-08-25 03:37:34

标签: ios xcode nsmutabledictionary

因此在运行时我初始化NSMutableDictionary,然后当用户点击某些按钮时,应用程序需要获取此按钮的名称,此名称将成为关键。然后他将点击另一个按钮,这个按钮的名称将被放入一个数组中,该数组将成为第一个按钮名称键的值。然而,稍后用户将继续这样做,并且如果他最终点击已经是字典中的值的按钮,则他按下的第二个按钮必须被添加到已经与该键相关联的阵列中。到目前为止,这是我的代码。

closestBeaconsDictionary是主词典。 closestBeaconName是构成键的变量,pinNumberName是必须放入数组的值。 nearestBeaconName和pinNumberName会根据用户按下的按钮不断变化。

//first, check to see if the key already exists. If not, then add the key to
//closestBeaconsDictionary and then create an array and add this array to the dictionary
//and then add pinNumberName to this array.
if ([closestBeaconsDictionary objectForKey:pinNumberName] == nil)
    {
        NSMutableArray *closestPinsToBeacon = [[NSMutableArray alloc] init];
        [closestPinsToBeacon addObject:pinNumberName];
        [closestBeaconsDictionary setObject:closestPinsToBeacon forKey:closestBeaconName];
    }
else
    {
        //what do I do here?? How do I access the dictionary that is at key:pinNumberName 
        //and then add an object to it?
    }

所以,我的问题基本上是我在else语句中添加了什么?我很困惑,因为在代码块运行后,closestPinsToBeacon基本上没有被销毁?

1 个答案:

答案 0 :(得分:0)

试试这个:

if ([closestBeaconsDictionary objectForKey:pinNumberName] == nil)
{
    NSMutableArray *closestPinsToBeacon = [[NSMutableArray alloc] init];
    [closestPinsToBeacon addObject:pinNumberName];
    [closestBeaconsDictionary setObject:closestPinsToBeacon forKey:closestBeaconName];
}
else
{
      NSMutableArray *arr = [[NSMutableArray alloc] init];
      arr = [[closestBeaconsDictionary objectForKey: closestBeaconName] mutableCopy];
      [arr addObject:pinNumberName];
      [closestBeaconsDictionary removeObjectForKey: closestBeaconName];
      [closestBeaconsDictionary setObject:arr forKey: closestBeaconName];
}

希望这会有所帮助.. :)