How to test whether NSString in Objective-C is empty?
#1 building
In any case, the best way is to check the length of a given string. If your string is myString, the code is:
int len = [myString length]; if(len == 0){ NSLog(@"String is empty"); } else{ NSLog(@"String is : %@", myString); }
#2 building
Just use one of the if else conditions as follows:
Method 1:
if ([yourString isEqualToString:@""]) { // yourString is empty. } else { // yourString has some text on it. }
Method 2:
if ([yourString length] == 0) { // Empty yourString } else { // yourString is not empty }
#3 building
Very useful article with NSDictionary support and a small change
static inline BOOL isEmpty(id thing) { return thing == nil || [thing isKindOfClass:[NSNull class]] || ([thing respondsToSelector:@selector(length)] && ![thing respondsToSelector:@selector(count)] && [(NSData *)thing length] == 0) || ([thing respondsToSelector:@selector(count)] && [thing count] == 0); }
#4 building
The first method is valid, but not if your string has spaces (@ ""). Therefore, you must clear this blank before testing.
This code clears all spaces on both sides of the string:
[stringObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ];
A good idea is to create a macro, so you don't have to type the following monster line:
#define allTrim( object ) [object stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ]
Now you can use:
NSString *emptyString = @" "; if ( [allTrim( emptyString ) length] == 0 ) NSLog(@"Is empty!");
#5 building
It's glamour for me
If NSString is s
if ([s isKindOfClass:[NSNull class]] || s == nil || [s isEqualToString:@""]) { NSLog(@"s is empty"); } else { NSLog(@"s containing %@", s); }