似乎在此循环中我有一个逻辑问题。我在尝试着:


循环myKeys(从字典中)以找到选定的玩家
在NSMutableArray(thePlayers)中为选定的播放器设置三个BOOL参数(是或否)
使用“ thePlayers”和“ myKeys”更新字典(selectedPlayerDict)
清空播放器并执行新循环,然后执行相同操作


当我分别选择每个播放器时,各个播放器具有以下参数:


  selectedPlayerDict:{汉娜=(0,0,1);}
  
  selectedPlayerDict:{
      AAAXXX =(
          1,
          1,
          1个
      );
  }


当同时选择两者时,意味着触发(如果([[theObjects objectAtIndex:3] == [NSNumber numberWithBool:YES])),则得到以下结果


  selectedPlayerDict:{
      AAAXXX =(
          0,
          0,
          1,
          1,
          1,
          1个
      );
  汉娜=(
          0,
          0,
          1,
          1,
          1,
          1个
      );
  }


对于上面的结果,我使用:


  // [thePlayers removeAllObjects]; // <<<<<<<<<<<<<<<<<<<<<<<<<<


当我更改并删除注释“ //”时:


  [thePlayers removeAllObjects]; // <<<<<<<<<<<<<<<<<<<<<<<<<<


我得到以下结果:


  selectedPlayerDict:{
      AAAXXX =(
      );
      汉娜=(
      );
  }


我使用的代码是:

for (NSString *myKeys in allTheKeys) {
    theObjects = [playerDict valueForKey:myKeys];

    if ([theObjects objectAtIndex:3] == [NSNumber numberWithBool:YES]) {

        //[thePlayers addObject:myKeys];

        NSLog(@"Spelare: %@ är vald", myKeys);
        NSLog(@">>>><<<<");

        // Check what difficulties level
        if ([theObjects objectAtIndex:0] == [NSNumber numberWithBool:YES]) { //hard
            NSLog(@"Player have diff HARD");
            [thePlayers addObject:[NSNumber numberWithBool:YES]]; //@"YES"];
        }
        else {
            NSLog(@"Player have NOT diff HARD");
            [thePlayers addObject:[NSNumber numberWithBool:NO]]; //@"NO"];
        }
        if ([theObjects objectAtIndex:1] == [NSNumber numberWithBool:YES]) { //medium
            NSLog(@"Player have diff MEDIUM");
            [thePlayers addObject:[NSNumber numberWithBool:YES]]; //@"YES"];
        }
        else {
            NSLog(@"Player have NOT diff MEDIUM");
            [thePlayers addObject:[NSNumber numberWithBool:NO]]; //@"NO"];
        }
        if ([theObjects objectAtIndex:2] == [NSNumber numberWithBool:YES]) { //easy
            NSLog(@"Player have diff EASY");
            [thePlayers addObject:[NSNumber numberWithBool:YES]]; //@"YES"];
        }
        else {
            NSLog(@"Player have NOT diff EASY");
            [thePlayers addObject:[NSNumber numberWithBool:NO]]; //@"NO"];
        }
        [selectedPlayerDict setValue:thePlayers forKey:myKeys];
        [thePlayers removeAllObjects];   //<<<<<<<<<<<<<<<<<<<<<<<<<<
    }

}
NSLog(@"selectedPlayerDict: %@", selectedPlayerDict);


我知道我在逻辑上可能做错了什么,但是我已经尝试了几个小时,试图了解我做错了什么。我不明白为什么dic的对象为空,因为我在更新字典后在循环末尾在数组中是“ removeAllObjects”?我已经尝试过“ setObject:forKey:”,但是没有运气。

最佳答案

问题是您正在对selectedPlayerDict中的每个键重复使用相同的数组。您将需要为每个循环迭代创建一个新的数组;否则,removeAllObjects将从单个数组中删除所有对象,该对象是字典中每个键的值。

附带说明一下,我想知道enum {Easy, Medium, Hard};是否可以满足您的需求,而不是3个BOOL-如果用户选择> 1个选项,会发生什么?

08-26 03:32