2

Possible Duplicate:
How do I test if a string is empty in Objective C?

I've been looking through Apple's documentation for a relatively basic function, and I cannot imagine that they wouldn't have a function to see if a string is either nothing/nil, or empty whitespace. I've Google searched for this too. The only things I'm finding are people giving advice on how to create their own function to test for an empty string.

In .NET, all I have to say is

If (String.IsNullOrEmpty(txtTextBox.Text)) {
// Action
}

Does Cocoa have an equivalent to the IsNullOrEmpty from .NET's String class?

Community
  • 1
  • 1
  • IMO that function is almost useless, even in .net. Treating `null` and the empty string as equivalent reeks of bad design to me. Most stings should never be `null`. – CodesInChaos Jan 03 '13 at 17:35
  • I'm really just concerned with checking for empty strings to make sure the user doesn't put spaces. So if I check to see if a string is @"", will it return true regardless of the number of empty characters? – user1946328 Jan 03 '13 at 17:54
  • Well that's the last thread I found before I posted my own. It doesn't really answer my question because the concern is white space, so checking the character count for 0 won't work. – user1946328 Jan 03 '13 at 17:56

1 Answers1

7

You can check if [string length] == 0. This will check if it's a valid but empty string (@"") as well as if its nil, since calling length on nil will also return 0.

EDIT: after reading your comment above I realize I missed one of your concerns about not only empty/nil, but also whitespace (which technically isn't empty). I'm not aware of a built in way to check all three of these conditions, but a simple solution would be to trim the whitespace out of the string during the test. For example:

NSString *str = @"   ";    //3 white spaces
if([str stringByTrimmingCharacterInSet: [NSCharacterSet whitespaceCharacterSet]] length] == 0)
{
        NSLog(@"String is empty, nil or full of whitespace!");
}

Result: String is empty, nil or full of whitespace!

You could also use whitespaceAndNewlineCharacterSet if that suits your needs better. I would suggest creating a separate method such as StringIsNullOrEmpty that accepts a string and performs the above test.

Source: How do I test if a string is empty in Objective C?

Community
  • 1
  • 1
StoriKnow
  • 5,738
  • 6
  • 37
  • 46