2011-07-17 11 views
-1

。例如在一個線程(因爲我不能在主迴路等)我有這樣的代碼:代碼守候在固定營業場所的觸摸屏幕

-(void) game { 
for (Players 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]; 

}

有沒有解決方案在固定的代碼位置等待UI事件? 當然沒有阻止主循環。

非常感謝您的幫助, jpdms

+2

整個構造看起來彆扭。做到基於事件,由主循環觸發。只需存儲狀態並作出相應的反應。 – Eiko

回答

1

首先,我強烈建議您閱讀蘋果的併發編程指南,包含在Xcode的文檔。一般來說,線程有更好的選擇,特別是在你提供的例子中。

然而:

如果game方法在單獨的線程執行的,則用信號通知線程適當的方法是使用NSCondition。創建一個實例並確保上面的代碼和觸摸處理程序都可以訪問它。

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

game方法,你就等着在這樣的條件:

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

你的遊戲線程就會休眠,直到病情有所暗示。在你觸摸的處理程序,你會做這樣的:

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

你有上面確實沒有然而演示了一個單獨的線程的需要,示例代碼。您可以非常輕鬆地在某處存儲currentPlayerIndex,然後轉到響應按鈕的按鈕處理程序中的下一個播放器。

此外,您必須確保任何UI更新實際發生在主線程。我希望您的線路如[ui showQuestion]正在主線程上排隊調用。 [ui performSelectorOnMainThread:@selector(showQuestion)];

你真的,真的,真的不應該使用一個單獨的線程爲此進行:在可可,你可以像很容易做到這一點。