I’d like to know if this is the correct way to avoid a memory leak in a Cocoa app.
My app has a method that updates an NSMenu‘s items:
//Remove and Release old Status Scan Menu:
if ([statusMenuScansMenu numberOfItems] !=0) {
for (NSMenuItem *menueItemToBeReleased in [statusMenuScansMenu itemArray]) {
[statusMenuScansMenu removeItem:menueItemToBeReleased];
[menueItemToBeReleased release];
}
}
//New Status Scan Menu:
for (MyObject* myObject in myArray) {
NSMenuItem * scanMenuItem = [[NSMenuItem alloc] init];
[scanMenuItem setTitle:[myObject name]];
[statusMenuScansMenu addItem:scanMenuItem];
}
As you can see, before adding new items I remove all previous items and send release to them. Then I add the new ones.
Is this the best way for memory management?
If I analyze my code in Xcode 4.1, it says that there is a potential memory leak.
It looks like how you are doing it should probably work OK, but it is kind of an odd way to go about it.
If you can require OS X 10.6+, your code could be consolidated to the following:
Note that by adding an
autoreleaseduring the creation of theNSMenuItemin the lower loop, there is no need to send the extrareleaseduring the menu item removal like in your code. In some sense, anNSMenuacts like anNSArraydoes with the sub menus and menu items it contains: it retains them. So since you are inserting the newly createdNSMenuItemdirectly into theNSMenu, it’s as if theNSMenuis taking ownership of the menu item. As such, you need to counteract the +1 retain count that you get from the alloc/init creation of the item to make sure you don’t get a memory leak. In your code, you were counteracting that +1 retain count by sending it an explicit/extra release during the menu item removal, which is kind of roundabout. In the above code that I posted, by adding theautoreleaseduring the creating in the lower loop, the only thing “holding on to” the menu items will the the menu. Then, later, when you call theremoveAllItemsmethod, the menu will send areleaseto each menu item, at which point their retain count should drop to 0, and they’ll be deallocated.If you need to support versions of OS X prior to 10.6, you can use the above code, except substitute
[statusMenuScansMenu md_removeAllItems]for[statusMenuScansMenu removeAllItems]. You can then create thismd_removeAllItemsmethod in a category onNSMenulike so: