如何在Objective-C中测试NSString是否为空?


当前回答

第一种方法是有效的,但如果字符串中有空格(@" ")则无效。所以在测试之前必须清除这些空白。

这段代码清除了字符串两边的所有空格:

[stringObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ];

一个好主意是创建一个宏,这样你就不必输入这一行怪物:

#define allTrim( object ) [object stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ]

现在你可以使用:

NSString *emptyString = @"   ";

if ( [allTrim( emptyString ) length] == 0 ) NSLog(@"Is empty!");

其他回答

if( [txtMobile.text length] == 0 )
{
    [Utility showAlertWithTitleAndMessage: AMLocalizedString(@"Invalid Mobile No",nil) message: AMLocalizedString(@"Enter valid Mobile Number",nil)];
}

你可以检查[string length] == 0。这将检查它是否是一个有效的空字符串(@"")以及它是否为nil,因为在nil上调用length也将返回0。

我这样写:

@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为nil,这个函数就永远不会被调用。它将返回false,这是所期望的。

另一个选项是用isEqualToString检查它是否等于@"":如下所示:

if ([myString isEqualToString:@""]) {
    NSLog(@"myString IS empty!");
} else {
    NSLog(@"myString IS NOT empty, it is: %@", myString);
}
if (string.length == 0) stringIsEmpty;