Alloc/Release question

Nibbie
Posts: 3
Joined: 2009.01
Post: #1
Hi guys,

I have a very basic question, I'm a java programmer and I'm not really familiar with alloc/release/..

I've an NSMutableArray called nextBalls containing UIImageViews:

Code:
[nextBalls addObject:[[UIImageView alloc] initWithImage:[UIImage imageNamed:[self randomImageName]]]];

My question: Do I have to release the allocated UIImageViews in my NSMutableArray nextBalls if not needed anymore? Or are they automatically released if I apply
Code:
[nextBalls removeObjectAtIndex:0];
?

Someone said I have to release all objects that i allocated, that's why im asking!

Thanks in advance Wink
Quote this message in a reply
Sage
Posts: 1,199
Joined: 2004.10
Post: #2
The array retains it on adding, releases it on removal. So think of it this way:

1) You create the image: retain=1
2) You add to the array: retain=2
3) You remove from the array: retain=1
4) You release it again: retain=0, it is deleted

This is where autorelease comes into play. Autorelease the image after creating it, and its retain will be decremented by one in the next event loop. This way you can basically forget about it, and when it's removed from the array, so long as nobody else has retained it it will be freed.

Code:
UIImageView *view = [[UIImageView alloc] initWithImage: [UIImage imageNamed:[self randomImage]]];
[nextBalls addObject: [view autorelease]];
Garbage collection is obviously preferable, but as manual memory management goes, retain/release/autorelease aren't too bad.
Quote this message in a reply
Nibbie
Posts: 3
Joined: 2009.01
Post: #3
Ok I do understand it now! Thank you for that excellent explanation! Wink
Quote this message in a reply
Member
Posts: 35
Joined: 2009.01
Post: #4
Note that most of Cocoa's default factory methods (those that obscure alloc, such as +[NSMutableArray array]) automatically apply autorelease, thus requiring a retain call.

So if in some object initialization method, you must either say myArray = [[NSMutableArray array] retain]; or myArray = [[NSMutableArray alloc] init];
Quote this message in a reply
⌘-R in Chief
Posts: 1,248
Joined: 2002.05
Post: #5
"Must" is not so. "Likely want to" is more appropriate. It depends on how the array is being used.
Quote this message in a reply
Member
Posts: 35
Joined: 2009.01
Post: #6
yes, of course =)

If a variable is intended for local use, retaining will result in memory leaks. Thanks for catching my mistake
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  yet another retain/release question... Andrew 3 2,782 May 30, 2005 03:21 PM
Last Post: Andrew