2

I've an instance of a class, which its delegate can only called once.

A view controller (View A) will call self.delegate = self, and has buttons to go to other view controller (VC).

In one of the VC, I need to call this instance and set the delegate again.

Initially I set the delegate in viewWillAppear but that won't work, because I'm loading the delegate data in viewDidLoad, and since viewDidLoad will run first, I can either set delegate in viewDidLoad or loadView.

Whereas removing delegate can be in dealloc, or viewWillDisappear, but if I'm presenting a VC, dealloc of View A won't be called isn't it? As the view is not removed yet.

So my question is, where to I set self.delegate = nil in view A?

If I'm using present VC method, where should I set and remove the delegate in View A? While in presented VC, I can just set and remove via viewDidLoad and dealloc.

Asking this in terms of best practice for app life cycle.

I've viewed iOS uiviewcontroller life cycle

Community
  • 1
  • 1
JackyW
  • 345
  • 2
  • 11

2 Answers2

5

I should have test this myself before asking.

Anyway, for others who might be interested to know as well.

View A will dealloc when going to other viewController (View B). So it is safe to remove delegate at View A's dealloc, and set the delegate at View B.

Where as if View B is presented by clicking on a in View A, dealloc won't be called. So in this case, it'll be better to use viewWillAppear and viewWillDisappear for setting and removing delegate respectively.

Cheers.

JackyW
  • 345
  • 2
  • 11
2

You have to setDelegate to self in viewDidAppear and set Delegate to nil in viewDidDisappear

avish manocha
  • 31
  • 1
  • 2