views:

755

answers:

1

I have some UIImageViews that are nested in UIViews, which group them together. They're owned by an view controller. As soon as the -viewWillDisappear method is called, I want to remove those UIImageViews with their UIViews alltogether, so that the memory gets freed up.

I call -release on the UIViews that contain the UIImageViews as subviews. Nothing else owns the UIImageViews. All I have is an instance variable to the UIView which groups the UIImageViews together.

So when I send -release to it, the retain count should become 0. But that's not a guarantee that I get more free memory, right? So, I also set myUIView = nil. Is that helpful / useful? How do you free up memory safely?

+2  A: 

The best thing to do in -viewDidDisappear (not -viewWillDisappear; you're still onscreen at that point) for this case is to call self.view = nil. That will dump the entire view controller's view, which will be automatically reloaded for you next time it's needed.

If you have any IBOutlets on those views, you need to set them to nil, too or they won't release. Assuming you have a setup like this:

@interface MyViewController : UIViewController
{
   UIImageView *_imageView;
}
@property (readwrite, retain) IBOutlet UIImageView *imageView;

@implementation MyViewController
@synthesize imageView = _imageView;

Then you need to call self.imageView = nil in your `-viewWillDisappear.

You generally should not call -release on your ivars except in their accessors and in -dealloc. The correct way to release them is to set them to nil using an accessor.

Caling -release when the retainCount is 1 will immediately call free(), which will recover memory. Remember, however, that other things may be retaining the object, including the autorelease pool, so you may not be certain what the retain count is at any given time.

I strongly advise people when they release a variable to immediately set it to nil. This doesn't impact the variable; it just protects you from chasing a pointer that you've released and so may now point to unallocated memory. So in -dealloc, I have lines that look like this:

[_stuff release]; _stuff = nil;
[_otherStuff release]; _otherStuff = nil;
Rob Napier
"Then you need to call self.imageView = nil in your `-viewWillDisappear" >>> you really don't the -viewDidDisappear?
Thanks
Sorry; backwards. Everything involving dropping views should be done in viewDidDisappear. You should wait until you're offscreen to start dropping things. If you drop UI components in viewWillDisappear, your animation can get messed up (since you animate between viewWillDisappear and viewDidDisappear).
Rob Napier