Swift performSelector:withObject:afterDelay:

目标C中有一个应用程序,我正在转换到Swift。 在Objective C中,我有这个方法:

[self.view performSelector:@selector(someSelector) withObject:self afterDelay:0.1f];

我正在与斯威夫特工作,我不知道如何做到这一点。 我试过了:

self.view.performSelector(Selector("someSelector"), withObject: self, afterDelay: 0.1)

这是我得到的错误: 'performSelector' is unavailable: 'performSelector' methods are unavailable

我会用什么来调用afterDelay方法?

UPDATE

以下是我最终的结果:

 extension NSObject { func callSelectorAsync(selector: Selector, object: AnyObject?, delay: NSTimeInterval) -> NSTimer { let timer = NSTimer.scheduledTimerWithTimeInterval(delay, target: self, selector: selector, userInfo: object, repeats: false) return timer } func callSelector(selector: Selector, object: AnyObject?, delay: NSTimeInterval) { let delay = delay * Double(NSEC_PER_SEC) let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(time, dispatch_get_main_queue(), { NSThread.detachNewThreadSelector(selector, toTarget:self, withObject: object) }) } } 

Swift 3

 DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) { // your function here } 

Swift 2

 let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) dispatch_after(dispatchTime, dispatch_get_main_queue(), { // your function here }) 

你可以这样做:

 var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("someSelector"), userInfo: nil, repeats: false) func someSelector() { // Something after a delay } 

SWIFT 3

 let timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(someSelector), userInfo: nil, repeats: false) func someSelector() { // Something after a delay } 

Swift是静态types的,所以performSelector:方法将在路边。

相反,使用GCD分配一个合适的块到相关的队列 – 在这种情况下,它可能是主队列,因为它看起来像你在做UIKit的工作。

编辑:相关performSelector:也明显从Swift版本的NSRunLoop文档 (“1 Objective-C符号隐藏”)中丢失,所以你不能直接跳过。 由于没有Swiftified NSObject我认为苹果在这里想的很清楚。