不可用

我在 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)
})
}
}
119825 次浏览

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

相反,使用 GCD 向相关队列分派一个合适的块ーー在本例中,它可能是主队列,因为看起来您正在执行 UIKit 工作。

编辑: 相关的 performSelector:也明显缺少从 NSRunLoop文档的 Swift 版本(“1目标-C 符号隐藏”) ,所以你不能直接跳入与该。鉴于这一点,以及它在 Swifated NSObject中的缺失,我认为苹果在这方面的想法非常清楚。

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

你可以这样做:

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
}