Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C returning alloc'd memory in a function == bad?

This is on the iPhone.

So what if I have a function like

- (SomeObject*)buildObject;

Do I need to pass in a variable that I have already alloc'd outside like

- (void)assignObject(SomeObject** out);

Or can I do

- (SomeObject*)buildObject
{
   return [[[SomeObject alloc] init] autorelease];
}

and use it like

SomeObject* obj = [[otherObject buildObject] retain];

I would like to do the last one, but as far as I've read this is undefined because autorelease only guarantees the object until the end of the function?

like image 358
DevDevDev Avatar asked May 29 '26 11:05

DevDevDev


1 Answers

In Objective-C, the memory management contract goes as follows: whoever calls alloc is responsible for calling release. If the constructing function calls [[[Class alloc] init] release] then the object is quickly created and destroyed.

To get around this, the constructing function would need to use autorelease as follows:

return [[[Class alloc] init] autorelease];

That registers the object to be released at the end of the current run loop unless something retains it, such as the caller of the constructing function. In your case, the second example is exactly what you want to do.

So:

- (SomeClass*) buildObject {
   return [[[SomeClass alloc] init] autorelease];
}

- (void) doSomething {
   c = [self buildObject];
   // Call [c retain] if you want c to stay around after the current run
   // loop is finished and clean it up later, e.g. in your delloc method.
}
like image 173
Bryan Kyle Avatar answered Jun 01 '26 01:06

Bryan Kyle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!