因此在运行时我初始化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
基本上没有被销毁?
答案 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];
}
希望这会有所帮助.. :)