0

可能重复:
在目标 c 中等待并通知等效项?

如何实现从 java 到 Objective c 的等待方法?我有代码: wait(a); 其中一个 - 整数变量。

4

3 回答 3

1

使用 GCD 的调度信号量怎么样?苹果关于调度信号量的文档说:

调度信号量类似于传统的信号量,但通常更有效。只有当调用线程因为信号量不可用而需要阻塞时,调度信号量才会向下调用内核。如果信号量可用,则不进行内核调用。有关如何使用调度信号量的示例,请参阅“使用调度信号量来调节有限资源的使用”。</p>

以下是我正在开发的纸牌游戏的示例。主线程等待直到某个条件(玩家完成他的回合)被批准。

   // 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-30T16:04:57.307 回答
0

如果要阻止另一个线程访问代码的关键部分,可以使用@synchronized指令。如果你只是为了等待而等待......你可以使用performSelector:withObject:afterDelay:方法NSObject

于 2012-07-30T15:48:46.790 回答
-3

你可以使用C函数sleep

sleep(5);  // sleep for 5 seconds

如果您想在不阻塞主线程的情况下等待,请使用:

[self performSelector:@selector(delayFunction:) withObject:nil afterDelay:5.0];
于 2012-07-30T15:35:22.360 回答