可能重複:
Wait and notify equivalent in Objective c?我如何實現從java到Objective C的等待方法?
我怎樣才能從Java到目標C實現wait方法? 我有代碼:wait(a);
其中a - Integer的變量。
可能重複:
Wait and notify equivalent in Objective c?我如何實現從java到Objective C的等待方法?
我怎樣才能從Java到目標C實現wait方法? 我有代碼:wait(a);
其中a - Integer的變量。
可以使用C函數睡眠
sleep(5); // sleep for 5 seconds
如果你要等待,而不會阻塞mainthread使用這樣的:
[self performSelector:@selector(delayFunction:) withObject:nil afterDelay:5.0];
,如果你想阻止另一個線程可以使用@synchronized指令從訪問代碼的關鍵部分。如果你只是想等待等待...你可以使用performSelector:withObject:afterDelay:
方法NSObject
如何使用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);
這是什麼等待呢? – 2012-07-30 15:34:38