Reputation: 12004
A beginners question about how to be memory efficient when using an UIView which contains a couple of images (ca. 500K). I guess if I handle this in the wrong way and call this view ten or twenty times, my app will crash (as I have leaked about 5-10 MB of RAM).
I have an UIView which I create programatically like so:
myView = [[UIView alloc] initWithFrame:0,0,0,0];
To this view I add a couple of images so that it eats up 500K of memory. After I'm done with this view, I'd like to free up the memory again. So I coded:
[myView removeFromSuperview];
myView = nil;
[myView release];
Is this the way to go? I am particularly uncertain about the last release call. Is myView not already released if I remove it from my superview and set it to nil?
Also, would it be a good idea to simply autorelease myView in the first instance, i.e.
myView = [[[UIView alloc] initWithFrame:0,0,0,0] autorelease];
I'd be grateful for any suggestions and corrections.
Upvotes: 2
Views: 1713
Reputation: 16658
You’re sending a release
message to nil
. The correct order for those statements would be:
[myView removeFromSuperview];
[myView release];
and optionally after that:
myView = nil;
For discussion on why to set to nil
:
The superview retains your view when you add it as a subview, and then releases it when you remove it. You still need you release your hold of it. You could use autorelease
when allocating it, but since you need to hold on to a pointer to it to be able to send removeFromSuperview
, the correct way is to send release
when you are done with that pointer (and then set that pointer to nil
).
Upvotes: 4
Reputation: 8169
About the autorelease, I think it's just a matter of personal preference, but I find it much easier to track memory issues when doing:
myView = [[[UIView alloc] initWithFrame:0,0,0,0] autorelease];
// add myView to wherever it belongs
.....
[myView removeFromSuperview];
myView = nil;
As others have pointed out, settting to myView
to nil
before you call release
is incorrect and will leak memory.
Upvotes: 1
Reputation: 28572
If you set your view to nil
before you call release
, you will leak the view and then send a message to nil. First you must release the view:
[myView removeFromSuperview];
[myView release];
Then you can set your variable to nil
to avoid sending a message to a deallocated instance.
Upvotes: 2