Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How do I test if an NSString is empty in Objective-C?

like image 216
Jamey McElveen Avatar asked May 22 '09 18:05

Jamey McElveen


People also ask

How do you check if a string is an empty string?

The isEmpty() method checks whether a string is empty or not. This method returns true if the string is empty (length() is 0), and false if not.

How do I find the nil value in Objective-C?

As this answer says: Any message to nil will return a result which is the equivalent to 0 for the type requested. Since the 0 for a boolean is NO, that is the result. Show activity on this post.

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

To check if a string contains another string in objective-c, we can use the rangeOfString: instance method where it returns the {NSNotFound, 0} if a 'searchString' is not found or empty (""). Output: string contains you!


2 Answers

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.

like image 182
Marc Charbonneau Avatar answered Sep 22 '22 11:09

Marc Charbonneau


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); } 
like image 43
Matt G Avatar answered Sep 21 '22 11:09

Matt G