Swift performSelector:withObject:afterDelay:不可用

时间:2014-06-11 18:43:08

标签: ios objective-c swift xcode6

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

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

我正在使用Swift,但我无法弄清楚如何做到这一点。我试过了:

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

以下是我收到的错误:'performSelector' is unavailable: 'performSelector' methods are unavailable

我会用什么电话来调用方法afterDelay

更新

这是我最终的结果:

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)
        })
    }
}

3 个答案:

答案 0 :(得分:149)

Swift 4

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

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 
})

答案 1 :(得分:108)

你可以这样做:

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
}

答案 2 :(得分:9)

Swift是静态类型的,因此performSelector:方法将被淘汰。

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

编辑:the Swift version of the NSRunLoop documentation(“1个Objective-C符号隐藏”)中也显着缺少相关的performSelector:,所以你无法直接使用它。有了这个并且它没有出现在Swiftified NSObject我认为苹果在这里想的很清楚。