2012-07-30 44 views

回答

-3

可以使用C函數睡眠

sleep(5); // sleep for 5 seconds 

如果你要等待,而不會阻塞mainthread使用這樣的:

[self performSelector:@selector(delayFunction:) withObject:nil afterDelay:5.0]; 
+3

回答直接問題,但是是一個可怕的答案。 「sleep()」永遠不是正確的答案。 :) – bbum 2012-07-30 15:36:25

+0

如果我想等待一些變量? – graffiti 2012-07-30 15:36:55

+0

Java'wait()'等待不斷,直到對象使用notify()來發送信號。它不是**和睡眠一樣。 – trojanfoe 2012-07-30 15:37:19

0

,如果你想阻止另一個線程可以使用@synchronized指令從訪問代碼的關鍵部分。如果你只是想等待等待...你可以使用performSelector:withObject:afterDelay:方法NSObject

1

如何使用GCD的調度信號? Apple's docs on dispatch semaphores請說以下內容:

調度信號燈與傳統的信號燈相似,但通常效率更高。只有當調用線程需要被阻塞,因爲信號量不可用時,調度信號纔會調用內核。如果信號量可用,則不進行內核調用。有關如何使用調度信號量的示例,請參閱「使用調度信號量調節有限資源的使用」。

以下是我正在開發的紙牌遊戲的一個示例。主線等待,直到某個條件(玩家輪到他)完成。

// a semaphore is used to prevent execution until the asynchronous task is completed ... 

    dispatch_semaphore_t sema = dispatch_semaphore_create(0); 


    // player chooses a card - once card is chosen, animate choice by moving card to center of board ... 

    [self.currentPlayer playCardWithPlayedCards:_currentTrick.cards trumpSuit:_trumpSuit completionHandler:^ (WSCard *card) { 

     BOOL success = [self.currentTrick addCard:card]; 

     DLog(@"did add card to trick? %@", success ? @"YES" : @"NO"); 

     NSString *message = [NSString stringWithFormat:@"Card played by %@", _currentPlayer.name]; 
     [_messageView setMessage:message]; 

     [self turnCard:card]; 
     [self moveCardToCenter:card]; 


     // send a signal that indicates that this asynchronous task is completed ... 

     dispatch_semaphore_signal(sema); 

     DLog(@"<<< signal dispatched >>>"); 
    }]; 


    // execution is halted, until a signal is received from another thread ... 

    DLog(@"<<< wait for signal >>>"); 

    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); 
    dispatch_release(sema); 
相關問題