How do I test if an NSString
is empty in Objective-C?
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.
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.
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!
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With