R – Can you alloc an object whose parent class uses the autorelease pool

memory-managementobjective c

I have a subclass that i use alloc and init to instantiate. In the init method I go

self = [self initWithRect:spriteManager.imageRect spriteManager:spriteManager.manager];

So the parent constructor is using the autorelease pool. So what happens here? If I try to release the object I get an error. Should I change my init method to be a convience constructor as well to conform to the alloc, copy, new ownership policy?

Best Answer

The superclass's initializer -initWithRect:spriteManager: does not put the object into the autorelease pool. The naming convention is that any -init… method sets up an object which you are responsible for releasing.

Xcode provides helpful code completion templates for init and dealloc methods. Just press control-comma and start typing "init" or "dealloc". (You can also type init and press control-comma.) The init template is

- (id) init
{
    self = [super init];
    if (self != nil)
    {
        // Your initializations
    }
    return self;
}

You'd replace self = [super init] with the line you wrote above.

The dealloc template is

- (void) dealloc
{
    // Your deallocations
    [super dealloc];
}

[super dealloc] invokes the superclass's -dealloc, which would take care of releasing whatever it set up in your -initWithRect:spriteManager: call (as well as anything it inherits from its superclass).

Related Topic