什么是Objective-C/Cocoa中Java的Thread.sleep()的等价物?

lev*_*evi 109 iphone cocoa-touch sleep objective-c

在Java中,您可以使用Thread.sleep()暂停当前线程的执行一段时间.在Objective C中有这样的东西吗?

smo*_*gan 157

是的,有+ [NSThread sleepForTimeInterval:]

(只是因为你知道未来的问题,Objective-C是语言本身;对象库(至少其中一个)是Cocoa.)

  • Thnx!<br>供将来参考,定义实际上是+ [NSThread sleepForTimeInterval:](因此,使用像[NSThread sleepForTimeInterval:0.1]). (6认同)
  • 对于那些想知道的人,[NSThread sleepForTimeInteval:]与[[NSThread currentThread] sleepForTimeInterval:]相同. (4认同)

Rok*_*iša 89

在Java中睡一秒钟:

Thread.sleep(1000);
Run Code Online (Sandbox Code Playgroud)

在Objective C中睡一秒钟:

[NSThread sleepForTimeInterval:1.0f];
Run Code Online (Sandbox Code Playgroud)


Ken*_*ner 40

你为什么睡觉?当您睡眠时,您正在阻止UI以及任何不在其他线程中加载的后台URL(使用NSURL异步方法仍在当前线程上运行).

你真正想要的是performSelector:withObject:AfterDelay.这是NSObject上的一个方法,你可以用它在某个预定的时间间隔之后调用一个方法 - 它会调度一个稍后会执行的调用,但是线程处理的所有其他东西(比如UI和数据加载)都会还在继续.

  • 睡觉对我来说非常有用.我可以模拟一些网络延迟,以确保我的应用程序正确响应.目前我正在测试本地Web服务器,所以一切都基本上是即时的. (43认同)
  • 睡眠是测试网络延迟的错误方法.请查看此问题的答案http://stackoverflow.com/questions/1502060/iphone-intermittent-network-testing,了解如何在模拟器中测试网络的可变速度.因为睡眠主线程会阻塞所有内容,所以你根本不会模拟网络延迟,而是更多地暂停应用程序. (6认同)

小智 7

当然,您也可以使用标准的Unix sleep()和usleep()调用.(如果编写Cocoa,我会继续使用[NSThread sleepForTimeInterval:].)


小智 5

如果使用NSThread sleepForTimeInterval(注释代码)进行休眠,则将阻止提取数据,但+ [NSThread sleepForTimeInterval:](checkLoad方法)将不会阻止提取数据.

我的示例代码如下:

- (void)viewDidAppear:(BOOL)animated
{
//....
//show loader view
[HUD showUIBlockingIndicatorWithText:@"Fetching JSON data"];
//    while (_loans == nil || _loans.count == 0)
//    {
//        [NSThread sleepForTimeInterval:1.0f];
//        [self reloadLoansFormApi];
//        NSLog(@"sleep ");
//    }
[self performSelector:@selector(checkLoad) withObject:self afterDelay:1.0f];
}

-(void) checkLoad
{
    [self reloadLoansFormApi];
    if (_loans == nil || _loans.count == 0)
    {
        [self performSelector:@selector(checkLoad) withObject:self afterDelay:1.0f];
    } else
    {
        NSLog(@"size %d", _loans.count);
        [self.tableView reloadData];
        //hide the loader view
        [HUD hideUIBlockingIndicator];
    }
}
Run Code Online (Sandbox Code Playgroud)