gpt4 book ai didi

objective-c - NSWindowWillCloseNotification 从数组中删除窗口后的 EXC_BAD_ACCESS

转载 作者:行者123 更新时间:2023-12-03 17:04:43 25 4
gpt4 key购买 nike

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

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

最佳答案

应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,以便在关闭时自行清理。

关于objective-c - NSWindowWillCloseNotification 从数组中删除窗口后的 EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12932713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com