如何在Objective-C中测试NSString是否为空?
当前回答
我这样写:
@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,这是所期望的。
其他回答
我见过的最好的解决方案之一(比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);
}
if(str.length == 0 || [str isKindOfClass: [NSNull class]]){
NSLog(@"String is empty");
}
else{
NSLog(@"String is not empty");
}
它就像if([myString isEqual:@""])或if([myString isEqualToString:@""])一样简单。
你最好使用这个类别:
@implementation NSString (Empty)
- (BOOL) isWhitespace{
return ([[self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]length] == 0);
}
@end
你有两个方法来检查字符串是否为空:
让我们假设你的字符串名字是NSString *strIsEmpty。
方法1:
if(strIsEmpty.length==0)
{
//String is empty
}
else
{
//String is not empty
}
方法2:
if([strIsEmpty isEqualToString:@""])
{
//String is empty
}
else
{
//String is not empty
}
选择上述任何一种方法,了解字符串是否为空。
推荐文章
- iPhone上UIView和UILabels的渐变
- keychain上的分发证书中缺少私钥
- 在实现API时,我如何避免在块中捕获自我?
- 如何创建一个Swift Date对象?
- Xcode 4在目标设备上说“finished running <my app>”——什么都没有发生
- 从另一个应用程序打开设置应用程序
- 快速提取正则表达式匹配
- 如何应用梯度的背景视图的iOS Swift应用程序
- 图书馆吗?静态的?动态吗?或框架?另一个项目中的项目
- 如何用SwiftUI调整图像大小?
- Xcode 6 gitignore文件应该包括什么?
- 如何在iPhone/iOS上删除电话号码的蓝色样式?
- 检测视网膜显示
- 如何在UIImageView中动画图像的变化?
- 如何从iPhone访问SOAP服务