views:

42

answers:

2

I have a button with IBAction, which shows another window:

-(IBAction)someButtonClick:(id)sender
{
    anotherView = [[NSWindowController alloc] initWithWindowNibName:@"AnotherWindow"];
    [anotherView showWindow:self];

}

I worry about memory management in here. I allocate an object in this IBAction and don't released it. But how can i do it? If i released this object after showing, window will closing immediately.

+2  A: 

The view is stored in an instance variable and you have access to it anywhere in your class. Release it in the code that dismisses the view.

spbfox
+1  A: 

Since anotherView is an instance variable you can release it in your dealloc method. But then you still have a memory leak, since every time your button is clicked a new instance of the window controller is created, but only the last one can be freed. You really should use accessors for this. Here is my suggestion:

- (NSWindowController *) anotherView;
{
    if (nil == anotherView) {
        anotherView = [[NSWindowController alloc] initWithWindowNibName:@"AnotherWindow"];
    }
    return anotherView;
}

- (void) setAnotherView: (NSWindowController *) newAnotherView;
{
    if (newAnotherView != anotherView) {
        [anotherView release];
        anotherView = [newAnotherView retain];
    }
}


- (void) dealloc;
{
    [self setAnotherView: nil];
    [super dealloc];
}


- (IBAction) someButtonClick: (id) sender;
{
    [[self anotherView] showWindow: self];
}

If you use a Objective-C 2.0 property you don't have to write the setter.

And also you should rename your instance variable, the name should reflect what it is. And a View is not a Window Controller.

Sven
Better yet, only create the window controller when it hasn't been created before. If it has, just send the one you already have the `showWindow:` message.
Peter Hosey
That is exactly what my code does. The getter `-anotherView` creates the window controller if there is none yet. If there is one already it just gets returned. So `-someButtonClick:` always gets the same object.
Sven