如何在Objective-C中测试NSString是否为空?
当前回答
if(str.length == 0 || [str isKindOfClass: [NSNull class]]){
NSLog(@"String is empty");
}
else{
NSLog(@"String is not empty");
}
其他回答
你可以很容易地检查字符串是否为空:
if ([yourstring isEqualToString:@""]) {
// execute your action here if string is empty
}
if( [txtMobile.text length] == 0 )
{
[Utility showAlertWithTitleAndMessage: AMLocalizedString(@"Invalid Mobile No",nil) message: AMLocalizedString(@"Enter valid Mobile Number",nil)];
}
我见过的最好的解决方案之一(比Matt G的更好)是这个改进的内联函数,我从一些Git Hub repo (Wil Shipley的一个,但我找不到链接):
// Check if the "thing" passed is empty
static 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);
}
第一种方法是有效的,但如果字符串中有空格(@" ")则无效。所以在测试之前必须清除这些空白。
这段代码清除了字符串两边的所有空格:
[stringObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ];
一个好主意是创建一个宏,这样你就不必输入这一行怪物:
#define allTrim( object ) [object stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet] ]
现在你可以使用:
NSString *emptyString = @" ";
if ( [allTrim( emptyString ) length] == 0 ) NSLog(@"Is empty!");
基于多个答案,我创建了一个可以使用的类别,结合@iDevAmit和@user238824答案。
具体来说,它是按照以下顺序进行的
检查null/nil 检查if字符串是否为空使用它的长度计数。 检查字符串是否为空白。
头
//
// NSString+Empty.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSString (Empty)
- (BOOL)isEmptyOrWhiteSpacesOrNil;
@end
NS_ASSUME_NONNULL_END
实现
//
// NSString+Empty.m
#import "NSString+Empty.h"
@implementation NSString (Empty)
- (BOOL) isWhitespace{
return ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0);
}
- (BOOL)isEmptyOrWhiteSpacesOrNil {
if(self == nil || [self isKindOfClass:[NSNull class]] || self.length==0 || [self isWhitespace] == YES) {
return YES;
}
return NO;
}
@end
/*
Credits
1. https://stackoverflow.com/a/24506942/7551807
2. https://stackoverflow.com/a/1963273/7551807
*/
用法: 当然,如果字符串为空,函数将永远不会被触发。第一种情况是为了增加安全保障。我建议在尝试使用此方法之前检查可空性。
if (myString) {
if [myString isEmptyOrWhiteSpacesOrNil] {
// String is empty
}
} else {
// String is null
}
推荐文章
- CFNetwork SSLHandshake iOS 9失败
- 请求失败:不可接受的内容类型:文本/html使用AFNetworking 2.0
- 缺少推荐的图标文件-该包不包含iPhone / iPod Touch的应用程序图标,像素为“120x120”,png格式
- 以编程方式创建segue
- 在Objective-C中@synchronized如何锁定/解锁?
- Xcode构建失败“架构x86_64未定义的符号”
- 如何使用Xcode创建。ipa文件?
- 动态改变UILabel的字体大小
- registerForRemoteNotificationTypes: iOS 8.0及以上版本不支持
- 新的自动引用计数机制是如何工作的?
- 如何测试对象在Objective-C中的类?
- 在iPhone上确定用户是否启用了推送通知
- 是否有可能禁用浮动头在UITableView与UITableViewStylePlain?
- 从Cocoa应用程序执行一个终端命令
- 错误ITMS-9000:“冗余二进制文件上传。火车1.0版本已经有一个二进制版本上传。