Andrew
Andrew

Reputation: 466

What is the value of the string @""?

I'm writing an iPhone application that uses a lot of editable text fields. I've been learning a lot about UITextFields and NSStrings by reading various references online, but there are some details that still elude me. When a user puts in an incorrect value for one of my text fields, I throw up an error message and put the text field back to the way it was before their input. For empty text fields, I've been doing this:

theTextField.text = @"";

Is this the best way to do this? I just came up with the idea myself, I don't know if there are any problems with it (other than the fact that it seems to work just fine so far).

Also, does @"" have the same value as a "nil" string? In other words, if I set a string to @"" and then call this:

if (myString) {...}

will the statement return true or false?

One last thing. When an NSString is initialized using this:

NSString *myString = [[NSString alloc] init];

what is that string's Length value?

Upvotes: 1

Views: 468

Answers (4)

entonio
entonio

Reputation: 2173

This is not an answer to the question, but may be the answer to what you're trying to do. If you're wondering whether you have to write if(str && str.length) to cover both nil and empty strings, you don't. You may use just if(str.length), since, in Objective-C, unknown messages to nil will return nil (so [a.b.c.d.e.f doStuff] will be nil if any of those values in the chain is nil). There is thus scarce need for specific nullity checks, unless what you want is precisely to determine nullity.

Upvotes: 2

user500
user500

Reputation: 4519

Check NSString's + string.

Upvotes: 0

jscs
jscs

Reputation: 64012

The important thing to understand here is that an NSString with no characters in it, such as @"" or [[NSString alloc] init] is still a valid object. All the consequences that Nick has stated follow from that.

In Objective-C, any valid object will be "True" in a boolean context;* nil is the only false object value.

Since these strings are valid objects, they do have a length, but because they contain no characters, the length is 0.

There are no problems with assigning an empty string object @"" to another string pointer, such as the text of your text field. Since the string with no characters is still a valid NSString object, this is exactly the same as assigning a string which does happen to have characters.


*Unlike so-called "scripting" languages like Python or Perl, where an empty string or collection evaluates to boolean false.

Upvotes: 3

Nick Weaver
Nick Weaver

Reputation: 47241

Using

theTextField.text = @"";

is absolutely ok. There should be no problems at all.

if (@"")

will evaluate to true. @"" is not the same as nil.

The length of

NSString *myString = [[NSString alloc] init];

is 0.

Upvotes: 2

Related Questions