NSString *tmpTxt = textField.text;
BOOL result = [textField becomeFirstResponder];
textField.text = tmpTxt;
This works 80% of the time, but occasionally:
- The whole app will crash.
- The text will开发者_开发知识库 still be deleted whatever happens.
Whats the best way for a textField to becomeFirstResponder and still retain its text value.
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.
精彩评论