NSTimer 不会调用私有函数作为选择器
NSTimer does not invoke a private func as selector
我正在研究一个要点:PasteboardWatcher.swift 我在其中调用了一个 NSTimer 对象,如下所示:
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
公开给其他人 类,因此我想将其标记为私有,但出于某种原因,当我这样做时,它会抛出以下异常:
-[PasteboardWatcher.PasteboardWatcher checkForChangesInPasteboard]: unrecognized selector sent to instance
如果我不将其标记为私有,它就可以完美运行。
有什么方法可以让这个方法保持私有,对其他方法隐藏起来类?
根据将Swift与Cocoa和Objective-C一起使用:
“标有 private 修饰符的声明不会出现在生成的 header 中。私有声明不会暴露给 Objective-C,除非它们也明确标有 @IBAction、@IBOutlet 或 @objc。”
摘自:Apple Inc.“将 Swift 与 Cocoa 和 Objective-C 结合使用(Swift 2 预发布版)。”电子书。 https://itun.es/us/utTW7.l
因此,您可以使用 @objc
标记您的函数以获得所需的行为。我刚刚在我使用 public 可见性的应用程序中对此进行了测试,因为我假设 Objective-C 根本看不到私有声明,并且在标记为私有并用 [=10 装饰时它可以工作=].
我刚看到这个相关问题:Swift access control with target selectors — 基本上是同一件事,但我认为你的措辞更笼统,因此严格来说不是重复的。
我正在研究一个要点:PasteboardWatcher.swift 我在其中调用了一个 NSTimer 对象,如下所示:
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
公开给其他人 类,因此我想将其标记为私有,但出于某种原因,当我这样做时,它会抛出以下异常:
-[PasteboardWatcher.PasteboardWatcher checkForChangesInPasteboard]: unrecognized selector sent to instance
如果我不将其标记为私有,它就可以完美运行。
有什么方法可以让这个方法保持私有,对其他方法隐藏起来类?
根据将Swift与Cocoa和Objective-C一起使用:
“标有 private 修饰符的声明不会出现在生成的 header 中。私有声明不会暴露给 Objective-C,除非它们也明确标有 @IBAction、@IBOutlet 或 @objc。”
摘自:Apple Inc.“将 Swift 与 Cocoa 和 Objective-C 结合使用(Swift 2 预发布版)。”电子书。 https://itun.es/us/utTW7.l
因此,您可以使用 @objc
标记您的函数以获得所需的行为。我刚刚在我使用 public 可见性的应用程序中对此进行了测试,因为我假设 Objective-C 根本看不到私有声明,并且在标记为私有并用 [=10 装饰时它可以工作=].
我刚看到这个相关问题:Swift access control with target selectors — 基本上是同一件事,但我认为你的措辞更笼统,因此严格来说不是重复的。