【问题标题】:NSTimer does not invoke a private func as selectorNSTimer 不调用私有函数作为选择器
【发布时间】:2015-09-05 23:01:02
【问题描述】:

我正在研究一个要点: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 access-control


    【解决方案1】:

    根据Using Swift with Cocoa and Objective-C

    “ 标有 private 修饰符的声明不会出现在生成的标头中。私有声明不会暴露给 Objective-C,除非它们也明确地用 @IBAction、@IBOutlet 或 @objc 标记。”

    摘自:Apple Inc.“将 Swift 与 Cocoa 和 Objective-C 结合使用(Swift 2 Prerelease)。”电子书。 https://itun.es/us/utTW7.l

    因此,您可以使用@objc 标记您的函数以获得所需的行为。我刚刚在我使用公共可见性的一个应用程序中对此进行了测试,因为我认为 Objective-C 根本看不到私有声明,并且当标记为私有并用 @objc 装饰时它可以工作。


    我刚刚看到了这个相关问题:Swift access control with target selectors — 基本上是一样的,但我认为你的措辞更笼统,所以严格来说不是重复的。

    【讨论】:

      猜你喜欢
      • 2015-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2013-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多