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

2019-01-04 04:20发布

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

30条回答
老娘就宠你
2楼-- · 2019-01-04 05:01

I put this:

@implementation NSObject (AdditionalMethod)
-(BOOL) isNotEmpty
{
    return !(self == nil
    || [self isKindOfClass:[NSNull class]]
    || ([self respondsToSelector:@selector(length)]
        && [(NSData *)self length] == 0)
    || ([self respondsToSelector:@selector(count)]
        && [(NSArray *)self count] == 0));

};
@end

The problem is that if self is nil, this function is never called. It'll return false, which is desired.

查看更多
聊天终结者
3楼-- · 2019-01-04 05:02

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!");
查看更多
在下西门庆
4楼-- · 2019-01-04 05:03

Its as simple as if([myString isEqual:@""]) or if([myString isEqualToString:@""])

查看更多
劫难
5楼-- · 2019-01-04 05:07

Just use one of the if else conditions as shown below:

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
}
查看更多
beautiful°
6楼-- · 2019-01-04 05:08

Simply Check your string length

 if (!yourString.length)
 {
   //your code  
 }

a message to NIL will return nil or 0, so no need to test for nil :).

Happy coding ...

查看更多
The star\"
7楼-- · 2019-01-04 05:09

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);
}
查看更多
登录 后发表回答