Proper allocation / release of UINavigationControllerDelagate

I have a UIViewController that should use the UINavigationControllerDelegate , specifically the willShowViewController method.

I set <UINavigationControllerDelegate> in my implementation, then I set the delegate for myself in viewDidLoad ( self.navigationController.delegate = self; ). Then I implement the willShowViewController method, and it works fine, however, when the view controller popped up from the stack, a memory leak occurs and my application crashes. I tried doing self.navigationController.delegate = nil; both in viewDidUnload and dealloc , but this does not help.

How can I implement this delegate for use in only one of my view controllers?

+4
source share
3 answers

viewDidUnload will not necessarily be called (mainly for handling low memory conditions), and by the time dealloc appears, the view controller is probably no longer in the navigation controller, so self.navigationController will be nil .

I suggest setting the delegate to nil in your implementation of viewWillDisappear: (and setting it to viewWillAppear: instead of viewDidLoad ).

Btw, you see the exact opposite of a memory leak here. A memory leak will be a memory that can no longer be reached and will never be freed. Here you have a memory that has already been freed (your view controller), but still refers to a (dangling) pointer, which causes a crash. An actual leak would usually not directly lead to a failure.

+6
source

You must either save a weak (non-persistent) link to the navigation controller or reset its delegate when it becomes clear that the navigation controller is about to release your controller. In truth, self.navigationController is no one else in dealloc self.navigationController , and viewDidUnload not sent when your controller viewDidUnload .

+4
source

you need to set the delegate in your implementation [viewDidAppear:] and set the delegate in your implementation [viewWillDisappear:] .

Tips: you should not set the delegate to nall in the dealloc implementation, because when dealloc is called, the viewController is unloaded from the navigation controller stack, so self.navigationController should be nil.

0
source

Source: https://habr.com/ru/post/1390582/


All Articles