Reputation: 1463
I have successfully setup notification observer using the code below:
func setupNotification {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "action:", name: notificationString, object: nil)
}
func action(notification: NSNotification) {
// Do something when receiving notification
}
However, I am not interested in the coding style above since there might be a chance that I could type or copy/paste wrong method name action:
.
So I tried to addObserver
in a different way: NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector(/* What to pass in here??? */), name: notificationString, object: nil)
, I don't know what to pass in selector: Selector(...)
.
XCode hints me: Selector(action(notification: NSNotification)
, but this is illegal.
In Objective C, I can easily pick up a method at this phase but I don't know how in Swift.
Have you tried this syntax? Let me know.
Thanks,
Upvotes: 0
Views: 657
Reputation: 15464
Not the direct answer for your question but I have an idea.
In swift instance methods are curried functions that take instance as first argument. Suppose you have a class like this.
class Foo: NSObject {
func bar(notification: NSNotification) {
// do something with notification
}
}
And somewhere in code you have an instance of Foo
.
let foo = Foo()
Now you can get bar
method as a variable like this
let barFunc = Foo.bar(foo)
Now imagine in the future NSNotificationCenter
has an api that lets you assign functions to it instead of selectors.
NSNotificationCenter.defaultCenter().addObserverFunction(barFunc, name: "notificationName", object: nil)
Though I don't like to use NSNotificationCenter
but It would be nice to see this kind of api in the future.
Upvotes: 0