开发者

About using convenient method and the time of their autorelease

This maybe too basic but I couldn't find an exact answer. I'll be happy to delete/close this post if anyone point me to similar po开发者_开发问答sts.

I want to call method "getString" to return a formatted string and set to my label like this:

-(NSString*) getString {
  NSString *result = [NSString stringWithFormat:@"blah blah %@", someOtherString];
  return result;
}

-(void) viewDidLoad {
  someLabel.text = [self getString];
}

This code worked for me, but I am concerned that result is allocated by a convenient method thus may be auto-released before it got retained by the label. Is it true? If so, when exactly would an object from convenient method get released?

Second question, if in case I have to use [NSString alloc] to create my own string object. Where and how should I release it?

Thanks in advance Leo


It isn't true that the object will be autoreleased before you retain it. The details of when the pool gets drained are unimportant to answer this question, except that it can't happen during your code unless you call drain or release on the pool. If your function calls another function, except in some specific edge cases both the function you call and the function you called from need to exit before that thread can do anything else. The autorelease pool is thread-specific.

To answer your second question, if you alloc an object you should release it when you've finished using it. Simple as that. That includes when you pass it to other code that needs it, because it should be up to that other code to claim ownership if it needs to.


This code worked for me, but I am concerned that result is allocated by a convenient method thus may be auto-released before it got retained by the label.

Yes, it will be autoreleased because it is returned by a method whose name does not contain new, alloc or copy. No, this won't happen before the calling method viewDidLoad returns.
In fact, the autorelease-pool, to which it's added will probably be the one set-up and teared-down by the runloop, so nothing is going to happen to it until the end of the current iteration through the runloop.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜