views:

135

answers:

1
NSString *tmpTxt = textField.text;
BOOL result = [textField becomeFirstResponder];
textField.text = tmpTxt;

This works 80% of the time, but occasionally:

  1. The whole app will crash.
  2. The text will still be deleted whatever happens.

Whats the best way for a textField to becomeFirstResponder and still retain its text value.

+1  A: 

If its clearing when it becomesFirstResponder, I guess is that you have @property(nonatomic) BOOL clearsOnBeginEditing set to YES.
Maybe, where ever you care creating textField, add textField.clearsOnBeginEditing = NO ; If you are using interface builder there is a check box in the properties for the textfield.

As to why its crashing most of the time...

the text property is defined as: @property(nonatomic, copy) NSString *text

The copy means when you assign a value to it, it will release the previous value, and then make a copy of the value passed in.

Your first line you are keeping a pointer around of the NSString object without calling retain on it. So when you call becomeFirstResponder with clearsOnBeginEditing is called it will set the new value to an empty NSString, which will release the old NSString that the UITextField had reference to. Since its the only thing that had ownership of it, that release call will call dealloc on the NSString, invalidating it.
Then you reassign it back to the text property where it attempts to copy the object that has been freed.

So to do it the way you have it, you will need to call retain and release:

NSString *tmpTxt = [textField.text retain];
BOOL result = [textField becomeFirstResponder];
textField.text = tmpTxt;
[tmpTxt release];

However all you need to do is set clearsOnBeginEdit to NO and you won't need that code.

Eld