C#和php都有sleep让线程休眠指定时间后再继续执行后面的代码,swift中应该如何呢?
首先,找一下objective-c版本是怎么做的[self performSelector:@selector(didTimeOut:) withObject:nil afterDelay:60];// 顺便演示下取消[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(didTimeout:) object:nil]
经过查找,swift中可以这么做:
var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("someSelector"), userInfo: nil, repeats: false)func someSelector() { // Something after a delay}
或者这样:
var delta: Int64 = 1 * Int64(NSEC_PER_SEC)var time = dispatch_time(DISPATCH_TIME_NOW, delta)dispatch_after(time, dispatch_get_main_queue(), { println("closures are " + txt) resolve()});// 当然没这么恐怖,time可以直接传数字时间dispatch_after(1, dispatch_get_main_queue(), { // your function here})
按C#的Threading.Thread.sleep(5000)
的写法,swift中有:
NSThread.sleepForTimeInterval(3)
可实际上,一个跟php完全一样的用法是完全可行的:
sleep(3)