Obj-C memory management for an NSView * instance variable

Posted by massimoperi on Stack Overflow See other posts from Stack Overflow or by massimoperi
Published on 2011-01-08T21:58:31Z Indexed on 2011/01/08 22:53 UTC
Read the original article Hit count: 152

My custom view has a subview as an instance variable. Here is a sample interface:

@interface MyCustomView : NSView {
    NSView *aSubview;
}

@end

Then, in the .m file, I initialize aSubView and add it to the custom view.

- (id)init
{
    self = [super initWithFrame:CGRectMakeFrame(0.0, 0.0, 320.0, 480.0);
    if (self) {
        aSubview = [[NSView alloc] initWithFrame(0.0, 0.0, 100.0, 100.0);

        [self addSubview:aSubview];
    }
    return self;
}

Where should I release aSubView?

In the -dealloc method?

- (void)dealloc
{
    [aSubView release];
    [super dealloc];
}

Or directly after adding it to the custom view in the -init method?

- (id)init
{
    [...]
    [self addSubview:aSubview];
    [aSubview release];
    [...]
}

Which one is the best implementation?

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about cocoa