I tried to process notifications between classes using NotificationCenter
, but it didn't work, so I'll leave a note of it. Since it is made to move by copy and paste, you can paste it on Playground etc. and check it.
Introducing the case that does not work first. Roughly speaking, the Sender
class posts the notification keyword test
when it is instantiated.
The Receiver
class will receive the notification keyword test
when instantiated, and will execute test ()
when it does.
import Foundation
class Sender {
let notificationCenter = NotificationCenter()
init() {
notificationCenter.post(name: NSNotification.Name(rawValue: "test"),
object: nil)
}
}
class Receiver {
let notificationCenter = NotificationCenter()
init() {
notificationCenter.addObserver(forName: .init(rawValue: "test"),
object: nil,
queue: nil,
using: { [unowned self] notification in
test()
})
}
func test() {
print("notification")
}
}
let receiver = Receiver()
let sender = Sender()
Here's when it works. The difference from if it didn't work is that you are using an instantiation of NotificationCenter
.
notificationCenter
→NotificationCenter.default
import Foundation
class Sender {
init() {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "test"),
object: nil)
}
}
class Receiver {
init() {
NotificationCenter.default.addObserver(forName: .init(rawValue: "test"),
object: nil,
queue: nil,
using: { [unowned self] notification in
test()
})
}
func test() {
print("notification")
}
}
let receiver = Receiver()
let sender = Sender()
The cause was that each class instantiated and used NotificationCenter
. It's natural that you can't do it because you don't use it across classes.
Still want to use the instantiated one! I will describe what to do in that case. It may be a rare case, but I think that this idea can be used in AVAudioPlayer
etc. Maybe this is more common.
import Foundation
class Sender {
let notificationCenter = NotificationCenter()
func send() {
notificationCenter.post(name: NSNotification.Name(rawValue: "test"),
object: nil)
}
}
class Receiver {
let notificationCenter: NotificationCenter
init(initNC : NotificationCenter) {
self.notificationCenter = initNC
notificationCenter.addObserver(forName: .init(rawValue: "test"),
object: nil,
queue: nil,
using: { [unowned self] notification in
test()
})
}
func test() {
print("notification")
}
}
let sender = Sender()
let receiver = Receiver(initNC: sender.notificationCenter)
sender.send()//notification
I changed a part of the source code when it didn't work as follows.
--Changed to send the notification of Sender
class bysend ()
instead ofinit ()
.
--Defined a variable of type NotificationCenter
in the Receiver
class.
By doing this, you can use a variable of type NotificationCenter
that is common between classes.
Recommended Posts