返回枚举ivar会导致EXC_BAD_ACCESS

时间:2012-01-29 12:34:45

标签: ios cocos2d-iphone exc-bad-access

我正在编写一个游戏,其中MainGameplay类通过将ivar设置为枚举值来跟踪其转向:

typedef enum {
  GAME_NOT_STARTED,
  PLAYER_1_TO_MOVE,
  PLAYER_2_TO_MOVE
} WhoseTurnIsIt;

然后GameBoard类检查移动尝试是否有效,并在MainGameplay.m中调用turnEnded:(WhoseTurnIsIt)turnreportTurnFailure:(WhoseTurnIsIt)turn

我在接收方法中尝试在MainGameplay中重新访问此返回值后,立即获得EXC_BAD_ACCESS。好像我应该保留一些东西,但你不能保留一个枚举。在调试器中,值存在,所以我不明白什么是不正确的访问。

这是在GameBoard中进行调用的代码:

-(void)buttonPressed:(id)sender {
  CCArray *kids = [[[CCDirector sharedDirector] runningScene] children];
  if (!mainScene) { // mainScene is an ivar on each the GameBoard's buttons.
    for (CCScene *s in kids) {
      // this looks crazy because the "main" scene is actually a controlling layer that has as a child the main gameplay layer:
      if ([s isKindOfClass:[ControlLayer class]]) {
        self->mainScene = (MainGameplay *)((ControlLayer *) s).gameLayer;
      }
    }
  }

  if (MOVE_NO_ERROR == [self checkMove:mainScene.turn]) {
    [self setMove:mainScene.turn];
    [mainScene turnEnded:mainScene.turn]; // This line and the next are the ones causing the EXC_BAD_ACCESS
  } else [mainScene reportTurnFailure:mainScene.turn]; // This line too.
}

编辑调用mainScene中的函数如下所示:

-(void) reportTurnFailure:(WhoseTurnIsIt)_turn {
  NSLog(@"MainScene still valid"); // This line works fine
  NSLog(@"Bzzzzzt. Player %@, try again", _turn); // This line crashes BUT _turn shows up with a proper value in the debugger.
}

1 个答案:

答案 0 :(得分:2)

_turn不是对象,但%@格式说明符表示参数是对象。请改用%i

-(void) reportTurnFailure:(WhoseTurnIsIt)_turn {
  NSLog(@"MainScene still valid"); // This line works fine
  NSLog(@"Bzzzzzt. Player %i, try again", _turn); // This line crashes BUT _turn shows up with a proper value in the debugger.
}