如何让iOS中的线程休眠几秒钟? [英] How to make thread sleep for seconds in iOS?

查看:1155
本文介绍了如何让iOS中的线程休眠几秒钟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在iOS环境中,是否可以让当前线程休眠几秒钟,然后执行我的代码? NSTimer,GDC或任何技术对我都没问题。

In iOS env, is it possible to make current thread sleep for seconds, then execute my code? NSTimer, GDC or any technique is okay for me.

推荐答案

如果你分享了你已经做过的事情会更好但是在这里你去。

It would be better if you shared what you have done but it here you go.

你可以选择几个选项:

选项1

// Standard Unix calls
sleep(); 
usleep();

关于 sleep 函数的一些文档可以是找到此处。你会发现它们实际上是 C 函数但是因为 Objective-C 是C的严格超集我们仍然可以使用 sleep usleep 函数。

Some documentation regarding the sleep function can be found here. You'll find that they are actually C functions but since Objective-C is a strict superset of C we can still use the sleep and usleep functions.

选项2

[NSThread sleepForTimeInterval:2.000];//2 seconds

Apple文档说明:


在给定的时间间隔内停留线程。

Sleeps the thread for a given time interval.

讨论

线程被阻塞时不会发生运行循环处理。

No run loop processing occurs while the thread is blocked.

选项3

 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 
                              1 * NSEC_PER_SEC),
                dispatch_get_main_queue(),
                ^{ 
                     // Do whatever you want here. 
                 });

Grand Central Dispatch 路线很漂亮做事的好方法。以下是 Grand Central Dispatch <的Apple文档/ a>这是一个非常好的阅读。

The Grand Central Dispatch route is a pretty good way of doing things as well. Here is the Apple Documentation for Grand Central Dispatch which is quite a good read.

还有一个问题可能非常有用如何在Objective-C中等待

There is also this question that might be pretty useful How to Wait in Objective-C

这篇关于如何让iOS中的线程休眠几秒钟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆