Jörgen Sigvardsson
Jörgen Sigvardsson

Reputation: 4887

autorelease interior pointer/object?

Suppose I have this code:

-(SomeOtherType*) getMyObject {
    SomeType someObject = [[SomeType alloc] init];
    // ... later on
    SomeOtherType toReturn = [[[someObject interiorObject] retain] autorelease];
    [someObject release];
    return toReturn;
}

The toReturn object, am I handling it correctly? I want to deliver it as an autoreleased object, but I do want to scrap someObject. Is this the pattern to transfer ownership? I've gone over it in my head and on paper, and it seems OK, but I'd rather be informed by someone more enlightened.

Edit This is a very contrived example, just to illustrate the problem at hand. someObject lives across many method calls, and in the end, I want to "dump its guts". This is NOT a Daily WTF example. Please don't ridicule me. :)

Upvotes: 2

Views: 110

Answers (2)

Evan
Evan

Reputation: 6161

The code you have provided in your question is correct. Lets go over why. When thinking about retain/release you need to think about ownership. Objects are typically owned by another object or within some particular scope. In this case getByObject's scope. The object you want to return is the interiorObject which is owned by someObject. But you need to release someObject before you return. The proper thing to do is take ownership of the interiorObject and return an autoreleased copy. And finally release or autorelease someObject.

If ownership was not acquired to the interiorObject before the release of someObject then the interiorObject could be deallocated and we would be returning a dangling pointer. The first time someone tries to send a message to it the program would likely crash.

Upvotes: 2

Paul.s
Paul.s

Reputation: 38728

I'm not 100% sure you need to do the retain / autorelease dance unless your expecting another thread to potentially deallocate your object?

- (SomeOtherType *)getMyObject
{
    SomeType someObject = [[SomeType alloc] init];
    // ... later on

    SomeOtherType toReturn = [someObject interiorObject];
    [someObject release];
    return toReturn;
}

The retain / autorelease dance will guarantee that the object hangs around to the end of the runloop even if another thread releases it's retains on it.

Upvotes: 1

Related Questions