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?
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With