views:

58

answers:

1

Hi all,

My view controller needs to know when it is poped out of the navigation controller stack, so that it can retain itself, wait and release itself later with another notification.

I intend to do like that when the view is sent dealloc message:

- (void)dealloc {
    if (self.isPerformingSomeTask) {
        self.isPopedOut = YES;
        [self retain];
        return;
    }
    [super dealloc];
}

But I think this is not a good solution? Any idea?

+4  A: 

This is an extremely bad idea.

  1. "-dealloc" is not the place to retain the object that is deallocated. If you want to be absolutely sure, that your object is not deallocated, then retain it upon construction, e.g. in "-viewDidLoad"
  2. "-dealloc" is not a way to detect that a view is popped from the navigation stack. You could be deallocated for any reason or the deallocation could be delayed even though you were popped from the stack
  3. If you want to detect, that the view is not displayed anymore, you should look for "-viewWillDisappear:"
  4. The pope has nothing to do with it, so don't pope out your views :-)
  5. If you need some object to receive the results of a long running task, probably your AppDelegate is a better receiver, not the view controller

EDIT: The following code refers to my comment below:

So you code should look like this

- (void) startMyLongTask {
  [self retain];
  // start the task
}

- (void) longRunningTaskReturns {
  // process results
  [self release];
}

- (void) dealloc {
  // as long as longRunningTaskReturns is not called
  // you will never come here
  [super dealloc];
}  
Jens
+1i -- a virtual up-vote for point 4!
Stephen Darlington
Hi, I am in the same team working for iphone with that guy (cong). Our problem is that we want to know when our view is pop out because when the view is poped out, the ViewController will be released and we want to save that ViewController until it finished its network task. So that, one of our solution is try to retain in dealloc
vodkhang
If you call "retain" in the routine that starts the network task, your view will never be deallocated until you say "-release". So you do not wait for "-dealloc"! Whenever the network task returns, you say "release" to your ViewController. If it has been popped out, it will be deallocated at that moment which is fine. If it was not popped out, things will continue without disturbance and dealloc will be called after it is popped out. As the network is not running now, everything is ok.
Jens
Code example added to my answer
Jens
Thanks a lot for your solution. I was trapped in another way of thinking:(
Thanh-Cong Vo