Reputation: 4100
I would like to remove a key from an NSMutableDictionary while enumerating, but if I do the app will crash because I have mutated it while enumerating it. this is the code:
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];
}
}
How can I do it?
Upvotes: 0
Views: 145
Reputation: 318804
The number of things wrong with your posted code or the number of needed improvements is high.
key
variable should have a type of MCPeerID
, not id
.[NCPeerID alloc]
.==
to compare two string values. Use isEqual:
key2
.Below is correct code that will do what you want:
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];
}
}
Upvotes: 4
Reputation: 119031
Copy the dictionary and enumerate the copy:
NSDictionary *enumerableDictionary = [BluetoothDeviceDictionary copy]
for (id key in enumerableDictionary) {
// edit BluetoothDeviceDictionary, don't use enumerableDictionary
}
Upvotes: 3