SpacePyro SpacePyro - 5 months ago 37
iOS Question

Dealloc called while method is still running

In a project I'm working on (I picked up this code and I've been trying to debug it), I have a function that gets called by an observer. The observer calls a method that updates data to be put on a screen. While this update is happening (it takes a few seconds for the updates to occur), a user can press the 'Back' button on the navigation bar, which causes a dealloc call to occur. While the method is running, the dealloc call releases all of the ivars, which eventually causes EXC_BAD_ACCESS when the method attempts to access the ivars. The structure of the update method is also enclosed with a


- (void)update {

// some code here...
// Also access ivars here.


What can be done to tell the controller to finish the method first before deallocating? I've tried running a while loop with a condition in the dealloc, but that doesn't seem efficient. It also never fully executes if the controller is released, and stays in a deadlock. I feel like the solution is simple, but my brain is fried from a long day at work and I can't think about it.


You can call retain on self to ensure the reference count does not reach zero while running a longer running method; and avoid the dealloc that way:

- (void) update {
    [self retain]

    // do work ...

    [self release]