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?
When you create
peopleStringit gets reference count of 1. Later, when you telllikeLabelto usepeopleStringfor its text, the reference count ofpeopleStringis incremented by 1. Now the reference count forpeopleStringis 2. WhenlikeLabelis released, presumably at the end of the event loop, the reference count ofpeopleStringis decremented by 1. But your instance ofpeopleStringis also getting its reference count decremented by 1 via the end of the event loop. SopeopleStringnow has a reference count of 0 and is removed from memory.See #6578 for a much better explanation.