如何在Objective-C中测试NSString是否为空?
当前回答
基于多个答案,我创建了一个可以使用的类别,结合@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
}
其他回答
你可以检查[string length] == 0。这将检查它是否是一个有效的空字符串(@"")以及它是否为nil,因为在nil上调用length也将返回0。
你最好使用这个类别:
@implementation NSString (Empty)
- (BOOL) isWhitespace{
return ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0);
}
@end
空字符串有两种方式:
1) @"" //不包含空格
2) @" " //包含空格
严格来说,这两个字符串都是空的。我们可以用条件一来写出这两个式子
if ([firstNameTF.text stringByReplacingOccurrencesOfString:@" " withString:@""].length==0)
{
NSLog(@"Empty String");
}
else
{
NSLog(@"String contains some value");
}
另一个选项是用isEqualToString检查它是否等于@"":如下所示:
if ([myString isEqualToString:@""]) {
NSLog(@"myString IS empty!");
} else {
NSLog(@"myString IS NOT empty, it is: %@", myString);
}
非常有用的帖子,添加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);
}
推荐文章
- iPhone上UIView和UILabels的渐变
- keychain上的分发证书中缺少私钥
- 在实现API时,我如何避免在块中捕获自我?
- 如何创建一个Swift Date对象?
- Xcode 4在目标设备上说“finished running <my app>”——什么都没有发生
- 从另一个应用程序打开设置应用程序
- 快速提取正则表达式匹配
- 如何应用梯度的背景视图的iOS Swift应用程序
- 图书馆吗?静态的?动态吗?或框架?另一个项目中的项目
- 如何用SwiftUI调整图像大小?
- Xcode 6 gitignore文件应该包括什么?
- 如何在iPhone/iOS上删除电话号码的蓝色样式?
- 检测视网膜显示
- 如何在UIImageView中动画图像的变化?
- 如何从iPhone访问SOAP服务