Objective-C multithreading, what happens when an object receives a dealloc during the execution of its methods? (And how to prevent this?)

I am writing an iPhone application and have come to this situation.

I have a view controller, myViewController, which will shut down whenever the user clicks the back button on the screen. There is a thread in the background that communicates with the remote server and can report the method, updateUI, method in myViewController.

What happens if an updateUI in the myViewController occurs in the message stream, but the user just clicks the back button at the right time to force myViewController dealloc while updateUI is still running?

My assumption is that the dealloc method will run and the application may crash if updateUI ends with a null pointer. Assuming this is the case, my current solution is:

[self retain];
// updateUI code here
[self release];

I am not sure if this is the best solution, as I feel that this is a common problem when working with multiple threads.

Is my assumption correct? If so, is there a better solution?

+3
source share
4 answers

, , , . , ( ).

+3

dealloc nil , - nil objective-c.

, , viewController , iOS 4 , GCD. , , viewController, , , -(void)dealloc ;.

+2

, , , - EXC_BAD_ACCESS.

, , . , .

+1

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


All Articles