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


当前回答

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

其他回答

你可以很容易地检查字符串是否为空:

if ([yourstring isEqualToString:@""]) {
    // execute your action here if string is empty
}

非常有用的帖子,添加NSDictionary支持以及一个小的变化

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);
}

简单地检查你的字符串长度

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

发送给NIL的消息将返回NIL或0,因此不需要测试NIL:)。

快乐编码…

if (string.length == 0) stringIsEmpty;

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