views:

36

answers:

2

I am creating a loading screen UIView which is added to a subview while some XML is parsed from some URL. Once the XML is returned, the loading screen is removed from its superview.

The question I have is how should I release this object?

In the code below, you'll see that I send removeFromSuperview to the loadingScreen, but I still have ownership of this object unless I release it. But, if I release it, there'll be nothing there to release in viewdidUnload and dealloc.

- (void)loadView {
  ...
  loadingScreen = [[LoadingScreen alloc] initWithFrame: self.view.frame];
  [self.view addSubview:loadingScreen]; //retain count = 2
}

-(void)doneParsing {
  ...
  [loadingScreen removeFromSuperview]; //retain count = 1
  [loadingScreen release]; //should i release the loading screen here?
}

- (void)viewDidUnload {
  [loadingScreen release]; //if viewDidUnload is called AFTER doneParsing, this
                           //will cause an exception, but the app might crash before
                           //doneParsing is called, so i need something here
}

- (void)dealloc {
  [loadingScreen release]; //if i've already released the object, i can't release here
}
+1  A: 

When you release loadingScreen, reset it to a nil value.

[loadingScreen release];
loadingScreen = nil;

[nil release] won't happen anything.

Toro
A: 

First, change the release line to [loadingScreen release], loadingScreen=nil;, or if loadingScreen is a retained property, instead use the equivalent self.loadingScreen=nil; Then when you get to viewDidUnload, you won't get an error because it is alright to release nil. Do the same in dealloc.

Peter DeWeese
Releasing it only in viewDidUnload is NOT sufficient, as viewDidUnload is not necessarily called during the lifetime of the controller.
imaginaryboy