How do I test if a string is empty in Objective-C? How do I test if a string is empty in Objective-C? ios ios

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


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


Marc's answer is correct. But I'll take this opportunity to include a pointer to Wil Shipley's generalized isEmpty, which he shared on his blog:

static inline BOOL IsEmpty(id thing) {return thing == nil|| ([thing respondsToSelector:@selector(length)]&& [(NSData *)thing length] == 0)|| ([thing respondsToSelector:@selector(count)]&& [(NSArray *)thing count] == 0);}


The first approach is valid, but doesn't work if your string has blank spaces (@" "). So you must clear this white spaces before testing it.

This code clear all the blank spaces on both sides of the string:

[stringObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ];

One good idea is create one macro, so you don't have to type this monster line:

#define allTrim( object ) [object stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ]

Now you can use:

NSString *emptyString = @"   ";if ( [allTrim( emptyString ) length] == 0 ) NSLog(@"Is empty!");