Search code examples
iosswiftselectornsnotificationcenter

How to pass arguments to the selector in NSNotificationCenter?


This code checks when the app becomes active and runs a specific method dataMain(). I added a argument to dataMain(productCode: String).

NSNotificationCenter.defaultCenter().addObserver(
            self,
            selector: "dataMain",
            name: UIApplicationDidBecomeActiveNotification,
            object: nil)

Is there any way I can pass the productCode argument to the selector?


Solution

  • If you have the productCode variable at the time of registering for this notification, then you could use a different notification observing method.

    let productCode = "A string"
    
    NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationDidBecomeActiveNotification,
        object: nil,
        queue: NSOperationQueue.mainQueue()) { (notification) -> Void in
            self.dataMain(productCode)
    }