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.
You’re sending a
releasemessage tonil. The correct order for those statements would be:and optionally after that:
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
autoreleasewhen allocating it, but since you need to hold on to a pointer to it to be able to sendremoveFromSuperview, the correct way is to sendreleasewhen you are done with that pointer (and then set that pointer tonil).