Reputation: 14557
I have a UIViewController
that needs to make use of the UINavigationControllerDelegate
, specifically the willShowViewController
method.
I am setting <UINavigationControllerDelegate>
in my implementation, then I am setting the delegate to self in viewDidLoad
(self.navigationController.delegate = self;
). Then I implement the willShowViewController
method and it works fine, however when the view controller is popped off the stack, there is a memory leak and my app is crashing. I've tried doing self.navigationController.delegate = nil;
in both viewDidUnload
and dealloc
but it doesn't help matters.
What is the correct way I can implement this delegate for use in just one of my viewcontrollers?
Upvotes: 4
Views: 552
Reputation: 66
you should setting the delegate is self in your [viewDidAppear:]
implementation and setting the delegate is nil in your [viewWillDisappear:]
implementation.
Tips: you shouldn't set the delegate is nil in dealloc implementation, because when the dealloc is called, the viewController is popped from the navigationcontroller stack so self.navigationController must be nil.
Upvotes: 0
Reputation: 23722
You should either keep a weak (non-retaining) reference to the navigation controller or reset its delegate when it becomes clear the navigation controller is going to pop your controller. The truth is, in dealloc
self.navigationController
is already nil, and viewDidUnload
is not sent when your controller gets popped.
Upvotes: 4
Reputation: 53561
viewDidUnload
will not necessarily ever be called (it's mostly for handling low memory conditions) and by the time dealloc
is called, the view controller is probably no longer contained in the navigation controller, so self.navigationController
would be nil
.
I'd suggest setting the delegate to nil
in your viewWillDisappear:
implementation (and setting it in viewWillAppear:
instead of viewDidLoad
).
Btw, you're seeing the exact opposite of a memory leak here. A memory leak would be memory that cannot be reached anymore and will never be freed. Here you have memory that has already been freed (your view controller), but is still referenced by a (dangling) pointer, leading to the crash. A real leak would usually not result directly in a crash.
Upvotes: 6