Young Min Sim
Young Min Sim

Reputation: 53

How Notification Center works in swift

By adding this,

class A {

init{
NotificationCenter.default.addObserver(self, selector: #selector(self.getData), name: NSNotification.Name(rawValue: "notify"), object: nil)
}

}

if there's some event named "notify" occurred, Notification center can execute 'self.getData()' in instance of A.

But I can't understand how it works. When NotificationCenter store instance of A, it gets instance as type 'Any', not 'A'.

I think if NotificationCenter try to call function 'getData()', it should do like,

let a = instance as! A

a.getData()

But this is so weird... if someone explain how it works, i will really appreciate it.

Thank you !

Upvotes: 0

Views: 265

Answers (1)

EmilioPelaez
EmilioPelaez

Reputation: 19892

NotificationCenter uses the Objective C runtime to send the messages, that's why you pass a selector, and the selector has to be tagged @objc.

The Objective C runtime is a lot more relaxed when it comes to types. It doesn't know what A is, it just knows it will have to send the message getData to it, and hopefully A will know what to do.

Before Selectors were improved in Objective C you would pass the name of the selector as a String, and any typos would result in a crash since A would not know what getDaya (for example) is.

They were improved to be checked when the code is compiled, but the underlaying mechanism didn't change.

Upvotes: 1

Related Questions