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];
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With