我想在枚举时从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];
}
}
我该怎么做?
答案 0 :(得分:3)
复制字典并枚举副本:
NSDictionary *enumerableDictionary = [BluetoothDeviceDictionary copy]
for (id key in enumerableDictionary) {
// edit BluetoothDeviceDictionary, don't use enumerableDictionary
}
答案 1 :(得分:3)
您发布的代码错误的数量或所需的改进数量很高。
key
变量的类型应为MCPeerID
,而不是id
。[NCPeerID alloc]
。==
来比较两个字符串值。使用isEqual:
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];
}
}