java中苹果好吃,iphone - Objective-C / Cocoa中Java的Thread.sleep()相当于什么?

本文探讨了Objective-C中如何使用[NSThread sleep]来实现类似Java的Thread.sleep功能,讨论了其在iOS开发中的应用,以及与暂停UI和后台任务执行的区别。同时提到了Unix sleep和usleep函数的使用。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值