Memory management of document modal panels


Graham Cox
 

I have a general question about memory management of a panel shown as a sheet.

As a general design pattern, I often have a class method that returns a new instance of a NSWindowController subclass for a given sheet. As per the usual rules, this instance is returned autoreleased.

I also usually provide a method in that class that will run the panel as a sheet on a nominated window, with a completion block. This method is essentially a wrapper around -[NSWindow beginSheet:completionHandler:], often with some additional setup private to my class.

The client of this code is typically my document subclass - in response to a user command, it will request a new instance of the panel via the class method, then run it as a sheet, passing its own -windowForSheet: as the parent.

The question I have is, should the panel controller be retained for the duration, or does the sheet display mechanism take care of that? It’s not clear to me who owns the NSWindowController instance while the sheet is in use. Logically it is the document, but because it just puts up the sheet and passes it a completion block (or not - sometimes the completion block is private to the window controller subclass, hidden within the -beginSheet wrapper), there’s nowhere other than within the completion block itself to release the controller. So should the completion block end up calling [self release] as its last step? What implications would that have for a retain loop caused by referencing self within the completion block?

As you can tell, this is a manual memory management question, but even in the ARC world, it’s not clear how ARC would resolve this question either.

—Graham

Join cocoa@apple-dev.groups.io to automatically receive all group messages.