iphone - Objective-C / Cocoa中Java的Thread.sleep()相当于什么?
在Java中,您可以使用Thread.sleep()暂停当前线程的执行一段时间。 在Objective C中有这样的东西吗?
6个解决方案
155 votes
是的,有+ [NSThread sleepForTimeInterval:]
(只是因为你知道未来的问题,Objective-C是语言本身;对象库(至少其中一个)是Cocoa。)
smorgan answered 2019-07-19T07:47:52Z
85 votes
在Java中睡一秒钟:
Thread.sleep(1000);
在Objective C中睡一秒钟:
[NSThread sleepForTimeInterval:1.0f];
Rok Strniša answered 2019-07-19T07:48:23Z
40 votes
你为什么睡觉? 当您睡眠时,您正在阻止UI以及任何不在其他线程中加载的后台URL(使用NSURL异步方法仍在当前线程上运行)。
你真正想要的是performSelector:withObject:AfterDelay。 这是NSObject上的一个方法,你可以用它在某个预定的时间间隔之后调用一个方法 - 它会调度一个稍后会执行的调用,但是线程处理的所有其他东西(比如UI和数据加载)都会 还在继续。
Kendall Helmstetter Gelner answered 2019-07-19T07:48:55Z
7 votes
当然,您也可以使用标准的Unix sleep()和usleep()调用。 (如果编写Cocoa,我会继续使用[NSThread sleepForTimeInterval:]。)
Bill Heyman answered 2019-07-19T07:49:19Z
5 votes
如果使用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];
}
}
wu liang answered 2019-07-19T07:49:51Z
0 votes
usleep()也可以用,因为我已经用它来暂停当前线程
j2emanue answered 2019-07-19T07:50:16Z