枚举时改变NSMutableDictionaly

时间:2013-09-14 19:52:51

标签: ios

我想在枚举时从NSMutableDictionary中删除一个键,但如果我这样做,应用程序会崩溃,因为我在枚举时已经突变了它。这是代码:

for(id key in BluetoothDeviceDictionary) {
    UIButton* btn = [BluetoothDeviceDictionary objectForKey:key];
    MCPeerID* DevicePeer = [MCPeerID alloc];
    DevicePeer = key;
    if (DevicePeer.displayName == peerID.displayName) {
        [btn removeFromSuperview];NSLog(@"LostPeer!!!!DEL");
        CountNumberOfBluetoothDevices = CountNumberOfBluetoothDevices - 1;
        [BluetoothDeviceDictionary removeObjectForKey:key2];
    }
}

我该怎么做?

2 个答案:

答案 0 :(得分:3)

复制字典并枚举副本:

NSDictionary *enumerableDictionary = [BluetoothDeviceDictionary copy]

for (id key in enumerableDictionary) {
    // edit BluetoothDeviceDictionary, don't use enumerableDictionary
}

答案 1 :(得分:3)

您发布的代码错误的数量或所需的改进数量很高。

  1. 变量和方法名称应以小写字母开头。
  2. key变量的类型应为MCPeerID,而不是id
  3. 没有理由致电[NCPeerID alloc]
  4. 您正在使用==来比较两个字符串值。使用isEqual:
  5. 发布的代码引用了一个不存在的变量key2
  6. 下面是正确的代码,可以执行您想要的操作:

    NSArray *keys = [BluetoothDeviceDictionary allKeys];
    for (NSUInteger k = keys.count; k > 0; k--) {
        MCPeerID *key = keys[k - 1];
        UIButton *btn = BluetoothDeviceDictionary[key];
        if ([key.displayName isEqualToString:peerID.displayName]) {
            [btn removeFromSuperview];
            NSLog(@"LostPeer!!!!DEL");
            CountNumberOfBluetoothDevices--;
            [BluetoothDeviceDictionary removeObjectForKey:key];
        }
    }