views:

1002

answers:

3

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.

+1  A: 

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.

TahoeWolverine
I'm speaking more toward clearing the text programmatically on viewWillAppear for editing objects, if that makes sense.
Brenden
A: 

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.

Dan Lorenc
+3  A: 

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.

Brad Smith
All responses are great, thanks. This is a good point here, though. Code consistency. Thanks all.
Brenden