0

When I was looking how to call a function from another view when this view is dismissing I found out that the NotificationCenter was a good solution so I tried to use it like this:

In my Main view (ViewController) where I want to call the function I put this:

NotificationCenter.default.addObserver(
            self,
            selector: #selector(ViewController.loyalty),
            name: NSNotification.Name("loyalty"),
            object: nil)

In my Second view before I call self.dismiss(animated: true, completion: nil) I call this to trigger the observe:

NotificationCenter.default.post(name: NSNotification.Name("loyalty"), object: nil)

Finally after the swift 4 update my function loyalty has @objc before the func and it is like this:

@objc func loyalty(){
}

PS I tried also with NSNotification.Name(rawValue: "loyalty")

Maybe I have forgot to do something?

Thanks in advance!

EDIT:

The function was executing after all I forgot to remove some arrays and that's why I thought it was not working.

Krunal
  • 77,632
  • 48
  • 245
  • 261
mike vorisis
  • 2,786
  • 6
  • 40
  • 74

2 Answers2

3

Apple documentation said :

In OS X 10.11 and iOS 9.0 NSNotificationCenter and NSDistributedNotificationCenter will no longer send notifications to registered observers that may be deallocated.

So I think your controller was deallocated after dismiss before it gets a notification.

kamwysoc
  • 6,709
  • 2
  • 34
  • 48
  • Thanks for your answer and good information too! The function was executing after all but I forgot to erase my arrays to get the correct result. (I found it out with printing at the start of the function). Sorry for wasting your time... – mike vorisis Oct 02 '17 at 13:33
2

I think the function should have a parameter to be called.

Try to edit your function to :

@objc func loyalty(_ notification : NSNotification){
}

And the selector becomes #selector(ViewController.loyalty(_:)

NB : Both register/post should be called in the same Thread

CZ54
  • 5,488
  • 1
  • 24
  • 39
  • Thanks for your answer and good information too! The function was executing after all but I forgot to erase my arrays to get the correct result. (I found it out with printing at the start of the function). Sorry for wasting your time... – mike vorisis Oct 02 '17 at 13:33