如何在垃圾收集的 Obj-C 中保留窗口而不保留指向它的指针?
我目前正在学习 Aaron Hillegaas 所著的著名的“Cocoa Programming for OSX”。
在第 12 章中,他希望我创建一个“关于”窗口
[BOOL] successful = [NSBundle loadNibNamed:@"About" owner:self];
,使用该窗口本身效果非常好。但是,我正在使用垃圾收集器,并且由于我不保留指向窗口的指针,因此它被垃圾收集,因此在一两秒后消失。如果禁用垃圾收集,它会很好地工作。
有没有办法创建一个窗口而不持有指向它的指针并且不让它被垃圾收集器吃掉?
I am currently working through the famous "Cocoa Programming for OSX" by Aaron Hillegaas.
In Chapter 12 he wants me to create an about window using
[BOOL] successful = [NSBundle loadNibNamed:@"About" owner:self];
which, by itself, works perfectly well. However, I am using the garbage collector and since I do not retain a pointer to that about window, it is garbage collected and thus disappears after a second or two. It works perfectly well if garbage collection is disabled.
Is there a way to create a window without holding a pointer to it and without having it eaten by the garbage collector?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以 使用
CFRetain
保留窗口,或使用NSGarbageCollector
的disableCollectorForPointer:
。但是,您很容易引入内存泄漏。确保用于关闭窗口的任何操作也会释放该窗口。如果传递给关闭操作的
sender
继承自NSView
,它将有一个window
属性您可以使用 来获取指向窗口的指针。然而,这并不是 Cocoa 设计的工作方式。在 Hillegaas 的书第 12 章中,他这样说:
如果您取消分配“关于”窗口,您的应用程序将崩溃或在有人第二次打开它时似乎没有响应。
编辑:另一种方法(但不会让您练习加载笔尖)是将“关于”窗口和一个 NSWindowController 添加到主笔尖(确保取消选中“关于”窗口的“启动时可见”属性)。这会使 Main.nib 变得混乱,但完全可以在 Interface Builder 中完成。连接:
showWindow:
操作连接到“关于”菜单项执行关闭:
操作。至于本课程的建议程度,苹果有话要说:
You can retain the window with
CFRetain
, or useNSGarbageCollector
'sdisableCollectorForPointer:
. However, you can easily introduce a memory leak. Make sure whichever action you use to close the window also releases the window.If the
sender
passed to the close action inherits fromNSView
, it will have awindow
property that you can use to get a pointer to the window.However, this is not how Cocoa is designed to work. In Chapter 12 of Hillegaas' book, he has this to say:
If you deallocate the About window, your app will either crash or appear not to respond the second time someone opens it.
Edit: An alternative (but one that doesn't give you practice in loading nibs) is to add the About window an an NSWindowController to the main nib (make sure you uncheck the About window's "Visible At Launch" attribute). This makes a mess of Main.nib, but can be done entirely in Interface Builder. Connect:
showWindow:
action to the About menu itemperformClose:
action.As for how advisable this course is, Apple has this to say: