I have a class that handles the notification. I can add the observer to NotificationCenter but the handles method never executes. If I move the same method into the class that adds the observer it works fine.
I've tried putting it in the class and it works fine just not from a different object. This is on Swift 4.2. I have also printed out all the observers via: print("Exp - NC - \(NotificationCenter.default.debugDescription)")
and can see the observer was added for the .purchase
name.
// Works
SomeClass.swift
// Works assuming notify handler is in this class
NotificationCenter.default.addObserver(self, selector: #selector(notify(_:)), name: .purchase, object: nil)
// Does not work
MyObserver.swift
import Foundation
@objc
public class MyObserver: NSObject {
@objc
public override init() {
print("Observer here creating a new instance")
}
@objc public func onNotification(_ notification: Notification) {
print("Observer 1 here notifying event")
}
}
SomeClass.swift
let myObserver = MyObserver()
NotificationCenter.default.addObserver(myObserver, selector:
#selector(myObserver.onNotification(_:)), name: .purchase, object:
nil)
Note: .purchase is an extension of Notification.Name
I would expect it to notify via the myObserver class as well. Seems like it only works with self
. The only difference is the observer is a custom object instead of self