Alessandro
Alessandro

Reputation: 4100

Mutate NSMutableDictionaly while enumerating

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

Answers (2)

rmaddy
rmaddy

Reputation: 318804

The number of things wrong with your posted code or the number of needed improvements is high.

  1. Variable and method names should begin with lower case letters.
  2. The key variable should have a type of MCPeerID, not id.
  3. There is no reason to call [NCPeerID alloc].
  4. You are using == to compare two string values. Use isEqual:
  5. The posted code references a non-existent variable 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

Wain
Wain

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

Related Questions