Alternate way (using Selector) to set up notification observer

661 views Asked by At

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,

2

There are 2 answers

2
qwerty_so On

The syntax for a Selector is Selector("action:")

0
mustafa On

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.