|
From: | Bertrand Dekoninck |
Subject: | Re: Need advice about NSTextField, performClick IBAction, and memory management |
Date: | Fri, 14 Dec 2018 09:54:18 +0100 |
Le 14 déc. 18 à 07:09, Josh Freeman a écrit :
Hi Bertrand, On Dec 13, 2018, at 3:55 PM, Bertrand Dekoninck wrote:In InterfaceBuilder (not Gorm here but it should be the same), I've also connected the "performClick" action from the textField to the addButton, so that the createTask method is also called when I type on the "Enter" key of the keyboard after editing the textField.It works as expected, but I've got extra calls to createNewTask : when the textField has the focus, performClick is also sent when clicking on another widget or if I use the "tab" key to cycle into another widget.Is there a way to avoid these ?You can set the textfield to only send its action when Enter's pressed (instead of every time editing finishes): In Interface Builder, select the textfield, then show the Inspector panel. Under the Inspector's Attributes tab, switch the textfield's 'Send Action' mode from "End editing" to "Enter only". (You can also do this programmatically by sending the textfield's cell a setSendsActionOnEndEditing:NO message.)
Thanks a lot !
2) The second problem is a memory management problem : in the createNewTask, I create a NSString using alloc +init.If I release that string at the end of the method, I've got a segfault if I try to add more than two tasks in the tasklistThese three lines in createNewTask: cause the issue: NSString *string = [[NSString alloc] init]; string = [textField stringValue]; ...[string release];// With this, I've got an "exec_BAD_ACCESS" error when calling three times in a row createNewTask with the same string in textFieldThe first line sets 'string' to a retained, empty string object. The next line sets 'string' to the object returned by [textField stringValue], leaking the previous string object (its address was forgotten while it was still retained). 'String' then points to an object that wasn't retained by your code, so sending it a release message will cause it to deallocate while it's still referenced elsewhere (segfaulting if it's accessed after that).
I wasn't aware I didn't need to allocate first but only to pass the pointer of [textField stringValue] to my new string.
You can fix the issue by removing the first & third lines (empty- string allocation, release call), and moving the 'string' var definition to the second line:NSString *string = [textField stringValue];
Obviously then... Thanks a lot. Bertrand
[Prev in Thread] | Current Thread | [Next in Thread] |