Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove NSWindow from array after closing

I'm creating windows programmatically and then adding them to an array when I show them like this.

NSWindow *window = [[NSWindow alloc] initWithContentRect:frame styleMask:NSTitledWindowMask | NSClosableWindowMask | NSResizableWindowMask | NSMiniaturizableWindowMask backing:NSBackingStoreBuffered defer:NO];
window.delegate = self;
window.releasedWhenClosed = YES;    
[window makeKeyAndOrderFront:NSApp];
[_array addObject:window];

I need to remove the windows from the array when they are closed but I can't seem to get this to work. If I remove the window from my array in the -windowWillClose: delegate method like this my app crashes with EXC_BAD_ACCESS after the delegate method completes.

- (void)windowWillClose:(NSNotification *)notification
{
    NSWindow *window = notification.object;
    [_array removeObject:window];
}
like image 921
Berry Blue Avatar asked Oct 17 '25 23:10

Berry Blue


1 Answers

Set the window's releasedWhenClosed property to false, not true.

Setting that property to true essentially causes an extra release beyond what normal memory management would involve. If you're using ARC, then this is one release too many because ARC itself would do balanced retains and releases. (If you were not using ARC, then that release would be appropriate to balance the +alloc in your first code snippet which is otherwise not balanced. However, even in that case, I'd recommend writing code that does normal, balanced memory management and setting this property to false.)

Second, set the window's delegate property to nil before removing it from the array.

Finally, if that doesn't fix the issue, show the details of the crash, including the stack trace.

like image 147
Ken Thomases Avatar answered Oct 22 '25 04:10

Ken Thomases