Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
670 views
in Technique[技术] by (71.8m points)

swift - NSTimer does not invoke a private func as selector

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

where definition of checkForChangesInPasteboard function is:

func checkForChangesInPasteboard() {
        // definition continues..
}

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.

Is there any way I can keep this method as private, hiding it from other classes?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to Using Swift with Cocoa and 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.”

Excerpt From: Apple Inc. “Using Swift with Cocoa and Objective-C (Swift 2 Prerelease).” iBooks. https://itun.es/us/utTW7.l

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...