Search code examples
iosnsnotificationcenternsnotification

methods aren't getting called after adding class as observer for notifications


I have a class called CoreSpotlight(NSObject class), in this class I have methods that need to respond to notifications. I'm trying to create an instance of this class in the app delegate and I called the method to add the instance itself as observer.

func addCoreSpotLightAsObserverForItemInstallerNotifications() {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "addNewInstalledItemToSpotlightIndex:", name: "ItemInstallerItemInstalledNotification", object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "removeUninstalledItemFromSpotlightIndex:", name: "ItemInstallerItemUninstalledNotification", object: nil)
    NSLog("Corespotlight added as observer///////////////////////////////////////////")
}

This is how I'm calling the method in the app delegate in application didFinishLaunchingWithOptions

let coreSpotlightInstanceClass = CoreSpotlight()
    coreSpotlightInstanceClass.addCoreSpotLightAsObserverForItemInstallerNotifications()

For some reason the methods aren't responding to the notifications. Thank you in advance


Solution

  • You are creating your instance of CoreSpotlight as a local variable inside the didFinishLaunchingWithOptions function, so as soon as this function exits the object will be released.

    You should create an instance property to store the reference;

    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        var window: UIWindow?
    
        let spotlightHandler = CoreSpotlight()
    
        func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
            // Override point for customization after application launch.
    
            self.spotlightHandler.addCoreSpotLightAsObserverForItemInstallerNotifications()
            return true
        }
    

    Although your code would be cleaner if you just invoked addCoreSpotLightAsObserverForItemInstallerNotifications (I have to say this is a pretty terrible function name too) in the CoreSpotlight init function. Then you wouldn't need to do anything other than instantiate an instance of that class in retained variable.