Is autorelease returning an error in object c?

I am new to object c and trying to understand how / when an abstract is called. I understand a simple usage example:

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

What about this next case - this is an error because the object will be immediately released after leaving the makeBar scope?

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

What if the caller saves?

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

Thanks, Eric

+7
memory-management objective-c autorelease
source share
2 answers

In your second example, the anonymous object that you return will not be released as soon as the execution leaves the makeBar , but at the next iteration of the execution loop. This will give you the option to retain it in any method called by makeBar

So your last example is fine, as the hold counter will not drop below 0.

Do you have a problem with this?

+7
source share
 -(Bar*) makeBar { return [[[Bar alloc] init] autorelease]; } 

The second case is the preferred way to return an Objective-C object. With the exception of +alloc , +alloc -copy... and -create... , the method should not preserve ownership of the returned object, i.e. The save (change) account must be 0.

However, [[Bar alloc] init] forces the object to have keepCount +1 so that it must release it before returning. But -release immediately free the object, making the method useless. -autorelease is used for this - it is delayed -release , that is, the object will be released in the end, but not now, so other parts of the code can still interact with it, but the save account can still be balanced to 0.


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

You should not save it if you do not want to be a long-term owner of the property b .

+5
source share

All Articles