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. ==2 つの文字列値を比較するために使用しています。使用する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 に答える