1

假设我有一个名为“创建窗口”的菜单按钮,可以创建一个新窗口:

MyWindowClass * window = [MyWindowClass new];

为了保留它,我将它添加到一个可变数组中(声明并合成为 _articleArray = [NSMutableArray new];)

[_articleArray addObject:window]

这很好用。如果我包括:

NSLog(@"Windows in mem: %lu",_articleArray.count);

每次单击按钮时,数字都会增加,屏幕上会出现另一个窗口。

现在,如果我将选择器附加到此“创建窗口”函数以识别窗口何时关闭:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowClosed:) name:NSWindowWillCloseNotification object:window];

这会产生一个错误:

-(void) windowClosed:(NSNotification*)notification {
    [_articleArray removeObject:[notification object]];
    NSLog(@"Windows in mem: %lu",_articleArray.count);

当我按预期关闭窗口时,NSLog 会递减,但是一旦函数结束,它就会引发 EXC_BAD_ACCESS 错误(代码 13,地址 = 0,0)

0x7fff97878710:  movq   24(%rax), %rax

我很迷茫。数字递减,所以我只能认为该功能正在工作。那么这里发生了什么?

编辑:(lldb)线程回溯

* thread #1: tid = 0x1c07, 0x00007fff97878710 libobjc.A.dylib`objc_msgSend_vtable13 + 16, stop reason = EXC_BAD_ACCESS (code=13, address=0x0)
frame #0: 0x00007fff97878710 libobjc.A.dylib`objc_msgSend_vtable13 + 16
frame #1: 0x00007fff97571503 Foundation`__NSFireTimer + 80
frame #2: 0x00007fff993a6da4 CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
frame #3: 0x00007fff993a68bd CoreFoundation`__CFRunLoopDoTimer + 557
frame #4: 0x00007fff9938c099 CoreFoundation`__CFRunLoopRun + 1513
frame #5: 0x00007fff9938b6b2 CoreFoundation`CFRunLoopRunSpecific + 290
frame #6: 0x00007fff8df260a4 HIToolbox`RunCurrentEventLoopInMode + 209
frame #7: 0x00007fff8df25e42 HIToolbox`ReceiveNextEventCommon + 356
frame #8: 0x00007fff8df25cd3 HIToolbox`BlockUntilNextEventMatchingListInMode + 62
frame #9: 0x00007fff92ce3613 AppKit`_DPSNextEvent + 685
frame #10: 0x00007fff92ce2ed2 AppKit`-[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 128
frame #11: 0x00007fff92cda283 AppKit`-[NSApplication run] + 517
frame #12: 0x00007fff92c7ecb6 AppKit`NSApplicationMain + 869
frame #13: 0x0000000100006942 myApp`main + 34 at main.m:13
frame #14: 0x00007fff9094f7e1 libdyld.dylib`start + 1
4

1 回答 1

2

应OP的要求,此答案已从问题中的评论中移出

您需要确保NSWindowWillCloseNotification在销毁窗口之前移除观察者:

-(void) windowClosed:(NSNotification*)notification {
    NSWindow *window = [notification object];
    [[NotificationCenter defaultCenter] removeObserver:self
                                                  name:NSWindowWillCloseNotification
                                                object:window];
    [_articleArray removeObject:window];
    NSLog(@"Windows in mem: %lu",_articleArray.count);
    ...

并确保窗口的isReleasedWhenClosed属性设置为,YES以便在关闭时自行清理。

于 2012-10-17T14:41:32.577 回答