Note that there are some explanatory texts on larger screens.

plurals
  1. POBetter way to manage lifetime of instance created in class method
    text
    copied!<p>In a pet application I'm writing, on the main window, I have a few custom views aligned under each other, each with a label, a combobox and a button.</p> <p>Clicking the button invokes code that finds the combobox in the same view, and then calls the following function (a class method of <code>RVListEditorController</code>):</p> <pre><code>+ (void) editComboBox: (NSComboBox *) aComboBox { // Analyze says "possible leak", but both methods ending the panel will release the controller. RVListEditorController *controller = [[RVListEditorController alloc] initWithComboBox: aComboBox]; [NSApp beginSheet: [controller window] modalForWindow: [aComboBox window] modalDelegate: controller didEndSelector: NULL contextInfo: nil]; } </code></pre> <p>The code creates an instance of <code>RVListEditorController</code>. That controls a panel that allows me to edit the list in the combobox (remove items, sort items, etc.). It has, among other controls, two buttons that close it, Cancel and OK.</p> <p>The code for the two buttons is:</p> <pre><code>- (IBAction) closeSheetWithOK: (id) sender { [NSApp endSheet: editingPanel]; [editingPanel orderOut: self]; [comboBoxValues setArray: valuesCopy]; if (comboBoxValues.count &gt; 0) [editedComboBox setStringValue: [comboBoxValues objectAtIndex: 0]]; [self release]; } - (IBAction) closeSheetWithCancel: (id) sender { [NSApp endSheet: editingPanel]; [editingPanel orderOut: self]; [self release]; } </code></pre> <p>These are the only two buttons that close the sheet. My question is about the lifetime management of the instance. It is allocated in the class method, but then control is handed to Cocoa again and the class method ends. The only place I could find to release the instance is in the two handlers for the closing buttons. My problem is that <code>beginSheet:modalForWindow:modalDelegate:didEndSelector:contextInfo:</code> doesn't simply open the sheet and then waits until it closes again, returning a value how it was closed. If that were the case, I could close the instance in the class method, and I would feel better. </p> <p>My question: Is there perhaps a better way to handle the lifetime of the instance, or is there something in Cocoa that allows me to open a sheet window-modally and then wait for it to close again, so I could release the instance right after that? I can't think of any, but I am a relative newbie, after all. </p> <p>FWIW, the code works, so there are no errors. I am simply not very happy with the construct that I allocate something in a class method that must then be released in two instance methods of itself.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload