NSTimer 不调用私有函数作为选择器 [英] NSTimer does not invoke a private func as selector
问题描述
我正在研究一个要点:PasteboardWatcher.swift,其中我调用了一个像这样的 NSTimer 对象:
I am working on a gist: PasteboardWatcher.swift in which I invoked a NSTimer object like this:
func startPolling () {
// setup and start of timer
timer = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: Selector("checkForChangesInPasteboard"), userInfo: nil, repeats: true)
}
checkForChangesInPasteboard
函数的定义是:
func checkForChangesInPasteboard() {
// definition continues..
}
我不想将函数 checkForChangesInPasteboard
暴露给其他类,因此我想将其标记为私有,但出于某种原因,当我这样做时,它会引发以下异常:
I don't want to expose function checkForChangesInPasteboard
to other classes, therefore I want to mark it as private but for some reason when I do so, it throws below exception:
-[PasteboardWatcher.PasteboardWatcher checkForChangesInPasteboard]: unrecognized selector sent to instance
如果我不将其标记为私有,它就可以完美运行.
If I don't mark it as private it works perfectly.
有什么办法可以让这个方法保持私有,对其他类隐藏它吗?
推荐答案
根据将 Swift 与 Cocoa 和 Objective-C 结合使用:
"标有 private 修饰符的声明不会出现在生成的标头中.除非用@IBAction、@IBOutlet 或 @objc 显式标记私有声明,否则它们不会暴露给 Objective-C."
" Declarations marked with the private modifier do not appear in the generated header. Private declarations are not exposed to Objective-C unless they are explicitly marked with @IBAction, @IBOutlet, or @objc as well."
摘自:Apple Inc.将 Swift 与 Cocoa 和 Objective-C 结合使用(Swift 2 预发行版)."电子书.https://itun.es/us/utTW7.l
Excerpt From: Apple Inc. "Using Swift with Cocoa and Objective-C (Swift 2 Prerelease)." iBooks. https://itun.es/us/utTW7.l
因此,您可以使用 @objc
标记您的函数以获得所需的行为.我刚刚在我使用公共可见性的一个应用程序中对此进行了测试,因为我认为 Objective-C 根本看不到私有声明,并且在标记为私有并用 @objc
装饰时它可以工作.
So, you can mark your function with @objc
to get the desired behavior. I just tested this in one of my apps where I had used public visibility because I assumed that Objective-C couldn't see private declarations at all, and it works when marked as private and decorated with @objc
.
我刚刚看到这个相关问题:使用目标选择器进行快速访问控制 - 基本上是一样的,但我认为你的措辞更笼统,所以严格来说不是重复.
I just saw this related question: Swift access control with target selectors — basically the same thing but I think yours is phrased in a more general way so not strictly a duplicate.
这篇关于NSTimer 不调用私有函数作为选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!