退出NSThread

时间:2012-05-24 09:25:03

标签: objective-c ios nsthread

我正在写一个游戏。 我有StartScene类: 在StartScene.h中:

@interface StartScene : UIView <UITextFieldDelegate> {
    ...
    PlayScene* tView;
    NSThread* gameMechThread;
}

PlayScene是一个继承的类

@interface PlayScene : StartScene {
}

因此,当我调用PlayScene视图时,我会调用

- (void)gameMechThread {
    gameMechThread = [[NSThread alloc]initWithTarget:self selector:@selector(gameMech) object:nil];
    [gameMechThread start];
 }

gameMech是一种方法,可以执行所有主要游戏内容。我有一个暂停按钮和StartScene类中该菜单的所有按钮。现在的问题是重启按钮。 所以当我通过点击暂停按钮调用pause方法(即在StartScene类中)时,

tView.GameState=GamePaused;

这是在pause方法中执行的。游戏的状态发生了变化。 在PlayScene类中,我得到了一直被调用的暂停方法

-(void)pause {
    while (self.gameState==GamePaused) {
    }
    if (self.gameState == GameRestarted) {
//        self.threadStop = 2;
        [NSThread exit];
    }
//  if (gameMechThread.isCancelled) {
//       [NSThread exit];
//    }
}

所以游戏暂停了。当我点击重启按钮时

-(void)restart {
    [gameMechThread cancel];
    [tView.player stop];
    tView.gameState=GameRestarted;
    self.gameState=GameRestarted;
    ...
 //   while (tView.threadStop != 2) { }
 //   tView.threadStop = 1;
    while (gameMechThread.isExecuting) { }

    [tView removeFromSuperview];
    [self startGame];
}

被召唤。一个问题是[gameMechThread cancel];,但

if (gameMechThread.isCancelled) {
       [NSThread exit];
}

无法正常工作,所以我现在评论它。 threadStop是一个属性,但在PlayScene类中,它不会在主线程上更改,因此该条件也无法正常工作。

现在问题是(gameMechThread.isExecuting)。虽然在执行[NSThread exit];之前调用了条件,但程序在执行[NSThread exit];之前不会保持状态,就好像该线程已经停止一样。 在调用([self startGame];)中的新线程之前,你可以帮助删除线程。

1 个答案:

答案 0 :(得分:0)

在NSThread中使用return

if (gameMechThread.isCancelled) {
       return;
}