开发者

Is return autorelease a bug in objective c?

开发者 https://www.devze.com 2022-12-20 06:05 出处:网络
I am new to objective c and am trying to understand how/when autorelease is called. I understand the simple use case of:

I am new to objective c and am trying to understand how/when autorelease is called. I understand the simple use case of:

- (void) foo {
    Bar *b = [[[Bar alloc] init] autorelease];
    [self doSomething:b];
  }

What about this next case -- is this a bug, because the object will be immediately released upon leaving the scope of makeBar?

-(Bar*) makeBar
{
    return [[[Bar alloc] init] autorelease];
}

What if the cal开发者_如何学Goler does a retain?

Bar *b = [[self makeBar] retain];

Thanks, -Eric


In your second example, the anonymous object you're returning will not be released as soon as the execution leaves the scope of makeBar but on the next iteration of the run loop. This will give you the opportunity to retain it in whatever method has called makeBar

So your final example is ok since the retain count will not drop below 0.

Are you having trouble with it?


-(Bar*) makeBar
{
    return [[[Bar alloc] init] autorelease];
}

The 2nd case is the preferred way to return an Objective-C object. Except +alloc, -copy... and -create..., the method should retain no ownership of the returning object, i.e. the (change of) retain count should be 0.

However, [[Bar alloc] init] makes the object to have retainCount of +1, to one should release it before return. But -release will immediate deallocate the object, making the method useless. That's why -autorelease is used — it is a delayed -release, i.e. the object will be released eventually, but not now, so other parts of code can still interact with it, yet the retain count can still be balanced to 0.


Bar *b = [[self makeBar] retain];

You should not retain it unless you want to be a long-term owner of the object b.

0

精彩评论

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