问题描述
我正在研究要点:,其中我调用了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
的tor如果我不将其标记为私有,则效果很好。
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预发行版)。 iBooks。
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不会调用私有函数作为选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!