Best way to clear a UITextField

43,367

Solution 1

Personally I would think less of the memory usage here and more on code-maintainability.

To me, It makes sense that a label always has a string. In the future someone might try to append a labels value, save it in a database, wrap it in xml, etc. An empty NSString in this case makes much more sense to me that a 0x0.

Solution 2

I usually do textFieldX.text = @""; just for clarity. This helps me remember that the value should be a string, and that I can pass it all the standard string methods.

Solution 3

I recommend you to use nil, because I discovered that when you use @"", the placeholder is not aligned in the center(if it must be aligned). Look, how I changed my code to get placeholder aligned properly.

 wordTextField.textAlignment = UITextAlignmentCenter;
 //wordTextField.text = @"";
 wordTextField.text = nil;
 translationTextField.textAlignment = UITextAlignmentCenter;
 //translationTextField.text = @"";
 translationTextField.text = nil;

Solution 4

Strings always copy in Objective-C, so the second option is most likely creating another string, and then pointing to it. In that way, I think you're right.

To play devil's advocate, I would assume that the compiler optimizes option B to do something like option A anyway. Personally, I would always do option B because it's more readable as far as the end operation you want to accomplish.

UPDATE: I didn't find a way to accomplish your goal differently, but you may be interested in this tidbit (from Apple UITextField Docs):

clearButtonMode

Controls when the standard clear button appears in the text field.

@property(nonatomic) UITextFieldViewMode clearButtonMode

Discussion

The standard clear button is displayed at the right side of the text field as a way for the user to remove text quickly. This button appears automatically based on the value set for this property.

The default value for this property is UITextFieldViewModeNever.

I think this would allow you to setup functionality for the user to clear the text field.

Share:
43,367
user14322501
Author by

user14322501

Updated on January 15, 2020

Comments

  • user14322501
    user14322501 over 4 years

    For an IBOutlet UITextField, does it matter as far as memory management or other reasons how you clear the text value?

    textFieldX.text = nil
    

    or

    textFieldX.text = @"";
    

    In objective-c it is acceptable to message a nil object and @"" is a static NSString *. I'm not sure if every @"" points to the same object in memory or if it allocates a bunch of 1 byte null terminated strings.

    Not a big deal, just thought I'd ask the community. Thanks.