0

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

Dharmesh Patel
  • 131
  • 1
  • 5
  • 2
    Sounds like `myObserver` or `SomeClass` might be going out-of-scope? Where are you creating `SomeClass`, and are you retaining it? Same question for `myObserver`... – DonMag Feb 13 '19 at 20:55
  • @DonMag yeah the observer was being dealloc'ed. If i move the observer to a class level var then it retains the object in memory to take action on the notification. – Dharmesh Patel Feb 13 '19 at 21:10
  • @DonMag thanks for the help. – Dharmesh Patel Feb 13 '19 at 21:16

0 Answers0