问题
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?
回答1:
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 the NSMenuDidEndTrackingNotification
notification. It also works great.
Yes, removeItem
should release the menu item. If you have some custom NSMenuItem
subclass where you explicitly allocate some views, you'll of course have to implement the dealloc
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.
来源:https://stackoverflow.com/questions/6817214/when-to-remove-dynamic-nsmenuitems-from-an-nsmenu