在我的主启动线程中,我需要暂停代码并启动一个新线程并等到我得到用户输入。然后我想丢弃新创建的线程并回到主线程停止的地方。但是发生的事情是调用了新线程,但主线程继续执行代码。如何在不干扰用户使用界面按钮的情况下处理这个问题?我认为可能需要在我的 if(moveCount == 2) 语句中创建另一个 nscondition?或者我的主线程需要等待来自我的另一个线程的信号,通知用户输入被接收。
附加说明:我还希望原始线程以这样的方式暂停,以便我仍然可以在我的界面中使用我的 2 个 UIButton。
关于我收到的问题的更多附加说明:这是我正在制作的游戏。在我的一种方法中,中间代码的某个地方意味着在我的主线程中。这种方法决定了我向哪个方向移动,然后我得到一个标签差异,然后进行攻击。但有时可以进行 2 次攻击,因此此时用户可以在屏幕上单击 2 个按钮来决定进行哪种攻击。
我也很清楚,我现在不应该暂停主线程。如果是这样,还有什么选择?谢谢
NSCondition 和 NSThread
@property (strong, nonatomic) NSCondition *condition;
@property (strong, nonatomic) NSThread *aThread;
在我的 viewDidLoad 中创建以下内容。
// create the NSCondition instance
self.condition = [[NSCondition alloc]init];
// create the thread
self.aThread = [[NSThread alloc] initWithTarget:self selector:@selector(threadLoop) object:nil];
代码中间的某个地方..
if(moveCount == 2){
[self.aThread start];
}
// I need to get captureDecision from user from 2 buttons before continue.. How do I pause this thread when aThread is started. Then when capture decision is received discard aThread and start here.
NSLog(@"Capture Decision = %d", captureDecision);
if(captureDecision == 1){
tagDifference = newButton.tag - currentButton.tag;
}else{
tagDifference = currentButton.tag - newButton.tag;
}
}
线程方法
-(void)threadLoop{
NSLog(@"Thread Loop Triggered");
while([[NSThread currentThread] isCancelled] == NO)
{
[self.condition lock];
while(captureDecision == 0)
{
[self.condition wait];
}
[self.condition unlock];
}
[NSThread exit]; //exit this thread when user input is received
}