How do I test if an NSString
is empty in Objective C?
views:
10235answers:
5You 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.
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 have blank spaces (@" "
). So you must to clear this white spaces before test it.
This code clear all the blank spaces on both sides of one 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!");
You should better use this category:
@implementation NSString (Empty)
- (BOOL) empty{
return ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0);
}
@end
One of the best solution I ever seen (better than Matt G's one) is this improved inline function I picked up on some Git Hub repo (sorry I forgot) :
// Check if the "thing" pass'd is empty
static inline BOOL isEmpty(id thing) {
return thing == nil
|| [thing isKindOfClass:[NSNull class]]
|| ([thing respondsToSelector:@selector(length)]
&& [(NSData *)thing length] == 0)
|| ([thing respondsToSelector:@selector(count)]
&& [(NSArray *)thing count] == 0);
}