何时从 NSMenu 中删除动态 NSMenuItem
我有一个 NSMenu,其中包含许多动态项目。这些项目是在 NSMenuDelegate 的 menuNeedsUpdate 方法中创建的,并且每个项目都分配有一个representedObject。我希望修剪对象图,并希望在菜单关闭时通过删除所有动态项目(并在重新打开菜单时重新创建它们)来重新获得一些内存。我遇到的问题是确切地知道应该在哪里以及如何处理这个问题。
文档指出 NSMenu 的 menuDidClose 不是更新菜单内容的合适位置。我已经设置了一个通知来侦听 NSMenuDidEndTrackingNotification,并通过调用 NSMenu 的 removeItem: 方法来删除此时的动态项目。这是处理这种情况的正确方法吗?
最后,我能否确信在 NSMenuItem 上调用 removeItem 将正确地取消可能分配给它的任何自定义视图以及任何子菜单?
I have an NSMenu which contains a number of dynamic items. These items are created in NSMenuDelegate's menuNeedsUpdate method and are each assigned a representedObject. I'm looking to trim the object graph and hopefully regain a bit of memory when the menu is closed by removing all dynamic items (and having them recreated when the menu is re-opened). The issue I'm having is knowing exactly where and how this should be handled.
The documentation states that NSMenu's menuDidClose is not a suitable place to update the contents of a menu. I've setup a notification to listen for NSMenuDidEndTrackingNotification and am removing the dynamic items at that point with a call to my NSMenu's removeItem: method. Is this the correct way to handle this situation?
Finally, can I be assured that calling removeItem on an NSMenuItem will correctly nullify any custom views that may be assigned to it, as well as any submenus?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我最近遇到了这个问题。你是绝对正确的。
menuDidClose:
不是删除菜单项的地方。我尝试过,但它导致操作方法无法从菜单项发送。据我所知,我发现正确的解决方案是使用 NSMenuDidEndTrackingNotification 通知。它也很好用。是的,
removeItem
应该释放菜单项。如果您有一些自定义的 NSMenuItem 子类,您可以在其中显式分配一些视图,那么您当然必须根据需要实现 dealloc 方法。如果您正在使用垃圾收集,则根本不必担心这一点。无论如何,您应该始终使用仪器来确保没有任何泄漏。I had this problem recently. You're absolutely right.
menuDidClose:
is not the place to delete menu items. I tried it, but it caused action methods to not be sent from the menu items. I found that the correct solution is, as far as I can see, to use theNSMenuDidEndTrackingNotification
notification. It also works great.Yes,
removeItem
should release the menu item. If you have some customNSMenuItem
subclass where you explicitly allocate some views, you'll of course have to implement thedealloc
method as necessary. If you're using garbage collection, shouldn't have to worry about this at all. In any case, you should always use Instruments to make sure you're not having any leaks.