问题描述
如何检测NSString在Objective-C里是否为空?
原问题:How do I test if a string is empty in Objective C?
问题解答
回答1:Marc Charbonneau可以检查是否[string length] == 0。这将检查它是否是一个有效但是为空的字符串(@'')以及其是否为无值。因为调用无值的length也将返回0。
Matt G楼上的回答是正确的。但是我想借此机会介绍一下Wil Shipley总结的isEmpty,他分享在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);}
第一种方法是有效地,但是如果字符串有空格(@' ')的话就买不起作用了。所以必须在测试前清除空格。下面的代码能够清除字符串两边的所有空格
[stringObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ];
有个不错的方法是定义一个宏,这样你就不用输入这一长串代码了:
#define allTrim( object ) [object stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ]
现在你可以使用:
NSString *emptyString = @' ';if ( [allTrim( emptyString ) length] == 0 ) NSLog(@'Is empty!');
Rob我见过的最好的解决方法之一(比Matt G的更好)这种改进的内联函数,我在Git Hub报告里找到的:
// Check if the 'thing' pass’d is emptystatic 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);}
user238824你最好使用这个函数:
@implementation NSString (Empty) - (BOOL) empty{return ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0); }@end
chown另一个选择是使用isEqualToString检查是否等于@'',就像这样:
if ([myString isEqualToString:@'']) { NSLog(@'myString IS empty!');} else { NSLog(@'myString IS NOT empty, it is: %@', myString);}
Jim Thio我用的这个:
@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
问题是如果self无值, 这个功能就永远不会被调用。它将返回false,这是所需的。
Samir Jwarchan使用下面的if else条件之一就可以:方法1:
<strong>if([yourString isEqualToString:@'']){// yourString is empty. } else {// yourString has some text on it. } </strong>
方法 2:
if([yourString length] == 0){ // Empty yourString}else { // yourString is not empty}