开发者

Objective-C: when does an assigned object get deallocated

开发者 https://www.devze.com 2022-12-29 17:13 出处:网络
If I have a instance method and within this method I do something like this: NSString *peopleString = [peopleList componentsJoinedByString: @\", \"];

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开发者_如何学Python 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 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号