views:

99

answers:

2

If I have a instance method and within this method I do something like this:

NSString *peopleString = [peopleList componentsJoinedByString: @", "];
...
UILabel *likeLabel = [[UILabel alloc] initWithFrame:CGRectMake(16.0+6.0f, 4.0f, 252.0f, 12.0f)];
[likeLabel setText:peopleString];
[likeLabel setFont:[UIFont fontWithName:@"Arial" size:12]];
[likeRow addSubview:likeLabel];
[likeLabel release];

The componentsJoinedByString doesn't contain a new, copy or alloc, thus I don't have to release it. What I'm wondering though is, when my peopleString gets deallocated. Might it happen to early? Meaning, before I can set the text in my label. Should I better use a [[NSString alloc] initWithString:[peopleList componentsJoinedByString: @", "]]; and release it at the end of this method?

+1  A: 

Auto-released objects (like "peopleString" in your code) are released by an auto-release pool (NSAutoreleasePool), when the "drain" method is called.
AppKit creates an auto-released pool on each cycle of the event loop, and drains it at the end.
So while you're code is executing (in a method, for instance), the objects won't get deallocated.

Macmade
There is a small overhead to using autorelease pools (which can accumulate to become a big overhead), so in general, very loosely, it is better to use alloc/init followed by release. However: I rarely bother.
Paul Lynch
Or, you can create other instances of NSAutoreleasePool. That way, objects don't accumulate till the end of the event loop, and you're saving some performance, as all your objects will be deallocated at the same time. : )
Macmade
Thanks for the answers/comments Macmade and Paul.
znq
+1  A: 

When you create peopleString it gets reference count of 1. Later, when you tell likeLabel to use peopleString for its text, the reference count of peopleString is incremented by 1. Now the reference count for peopleString is 2. When likeLabel is released, presumably at the end of the event loop, the reference count of peopleString is decremented by 1. But your instance of peopleString is also getting its reference count decremented by 1 via the end of the event loop. So peopleString now has a reference count of 0 and is removed from memory.

See #6578 for a much better explanation.

jsumners
Thanks for the answer and pointing me to #6578
znq