开发者

waiting in the fixed place in the code for a touch on the screen

For example in a thread (because I can't wait in main loop) I have this code :

-(void) game {
for (Pl开发者_开发技巧ayers player in players) {
    if (player.type == IA) {        // computer plays
        answer = [player play];
    else {
         [ui showQuestion];          // user plays with the touch screen
         // here waiting for the answer touch 
         answer = ????????????????   // return from waiting after touch callback

     }
     [answersArray addObject:answer];
}
answer = [self bestAnswer : answersArray];
[ui showTheBestAnswer : answer];

}

Is there a solution to wait for an UI Event in a fixed code place ? without blocking the main loop of course.

Thank you very much for your help, jpdms


First of all, I highly recommend that you read Apple's Concurrency Programming Guide, included with the Xcode documentation. In general, there are much better alternatives to threads, especially in the example you provide.

However:

If the game method is executing on a separate thread, then the proper way to signal the thread is using NSCondition. Create an instance and make sure both the code above and the touch handler has access to it.

NSCondition *playerDidTouchCondition = [[NSCondition alloc] init];

In the game method, you wait on the condition like this:

[ui showQuestion];
[playerDidTouchCondition lock];
[playerDidTouchCondition wait];
[playerDidTouchCondition unlock];
// do something with answer

Your game thread will sleep until the condition has been signaled. In your touch handler you would do this:

answer = whatever the user did
[playerDidTouchCondition lock];
[playerDidTouchCondition signal]; // wake up one of the sleeping threads
[playerDidTouchCondition unlock];

The example code you have above really doesn't demonstrate the need for a separate thread, however. You could very easily store a currentPlayerIndex somewhere and proceed to the next player inside of the button handler for the answer button.

Also, you MUST ensure that any UI updates are actually happening on the main thread. I hope that your lines like [ui showQuestion] are queuing calls on the main thread. In Cocoa you can do this easily with something like: [ui performSelectorOnMainThread:@selector(showQuestion)];

You really, really, really should not be using a separate thread for this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜