0

我想在枚举时从 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];
    }
}

我该怎么做?

4

2 回答 2

4

您发布的代码有很多问题或需要改进的地方很多。

  1. 变量和方法名称应以小写字母开头。
  2. 变量的key类型应该是MCPeerID,而不是id
  3. 没有理由打电话[NCPeerID alloc]
  4. ==用于比较两个字符串值。利用isEqual:
  5. 发布的代码引用了一个不存在的变量key2

以下是正确的代码,可以满足您的要求:

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];
    }
}
于 2013-09-14T20:15:32.300 回答
3

复制字典并枚举副本:

NSDictionary *enumerableDictionary = [BluetoothDeviceDictionary copy]

for (id key in enumerableDictionary) {
    // edit BluetoothDeviceDictionary, don't use enumerableDictionary
}
于 2013-09-14T19:54:12.780 回答