Allen
Allen

Reputation: 6882

where I really should be adding and removing notification observers in Swift?

With Swift, something changed, for instance dealloc() can no longer be used in Swift-based ViewControllers instead deinit.

I searched, found somebody said that add notification observer in viewWillAppear method and remove in viewDidDisappear, and others said maybe init(coder aDecoder: NSCoder) & deinit is a good choice.

I really want to know what's the best programming practice?

Upvotes: 2

Views: 1069

Answers (2)

Mick MacCallum
Mick MacCallum

Reputation: 130193

It's not really a matter of which is better practice, it really depends on which best suits your needs.

If for example, you have a view controller that should respond to notifications it's observing until it is deinitialized, go with that route. Or, if you're doing things like updating the interface of the view controller based on information received in the notification, you may only need to do so when that view controller is actually visible, in which case viewWillAppear:/viewDidDisappear: are good options.

Upvotes: 1

Vitalii Gozhenko
Vitalii Gozhenko

Reputation: 9354

If you add notification observer in viewWillAppear, you can have a problem with such case:

    let detailsViewController = UIViewController(nibName: "DetailsViewController", bundle: nil);
    // your detailsViewController don't handle some notifications, because it isn't in view hierarchy yet, and viewWillAppear hasn't called yet
    // ...
    self.presentViewController(detailsViewController, animated: true, completion: nil);
    // Only after this code, your detailsViewController start to handle some notifications, because you declare adding notification observer in viewWillAppear

So I think you right - init(coder) and deinit() will be the better choice

viewWillAppear and viewDidDissapear will be the good choice, when you need to handle view-based notifications - for example keyboard appearance

Upvotes: 0

Related Questions