如何在Objective-C中测试NSString是否为空?
当前回答
你可以很容易地检查字符串是否为空:
if ([yourstring isEqualToString:@""]) {
// execute your action here if string is empty
}
其他回答
只需使用一个if else条件,如下所示:
方法1:
if ([yourString isEqualToString:@""]) {
// yourString is empty.
} else {
// yourString has some text on it.
}
方法2:
if ([yourString length] == 0) {
// Empty yourString
} else {
// yourString is not empty
}
你可以很容易地检查字符串是否为空:
if ([yourstring isEqualToString:@""]) {
// execute your action here if string is empty
}
斯威夫特版本
即使这是一个Objective C问题,我需要在Swift中使用NSString,所以我也会在这里包括一个答案。
let myNSString: NSString = ""
if myNSString.length == 0 {
print("String is empty.")
}
或者NSString是可选的:
var myOptionalNSString: NSString? = nil
if myOptionalNSString == nil || myOptionalNSString!.length == 0 {
print("String is empty.")
}
// or alternatively...
if let myString = myOptionalNSString {
if myString.length != 0 {
print("String is not empty.")
}
}
正常的Swift String版本是
let myString: String = ""
if myString.isEmpty {
print("String is empty.")
}
请参见:检查Swift中的空字符串?
我检查了一个空字符串使用以下代码:
//Check if we have any search terms in the search dictionary.
if( (strMyString.text==(id) [NSNull null] || [strMyString.text length]==0
|| strMyString.text isEqual:@"")) {
[AlertView showAlert:@"Please enter a valid string"];
}
马克的回答是正确的。但我想借此机会引用Wil Shipley在他的博客上分享的一般化的isEmpty:
static inline BOOL IsEmpty(id thing) {
return thing == nil
|| ([thing respondsToSelector:@selector(length)]
&& [(NSData *)thing length] == 0)
|| ([thing respondsToSelector:@selector(count)]
&& [(NSArray *)thing count] == 0);
}
推荐文章
- 如何删除默认的导航栏空间在SwiftUI导航视图
- 如何在iOS中使用Swift编程segue
- Swift -整数转换为小时/分钟/秒
- Swift:声明一个空字典
- 为什么ARC仍然需要@autoreleasepool ?
- 在成功提交我的应用程序后,“太多符号文件”
- 首先添加一个UIView,甚至是导航栏
- 我如何改变UIButton标题颜色?
- 在Swift中如何调用GCD主线程上的参数方法?
- NSLayoutConstraints是可动画的吗?
- iOS -构建失败,CocoaPods无法找到头文件
- Xcode 4挂在“附加到(应用程序名称)”
- CFNetwork SSLHandshake iOS 9失败
- 请求失败:不可接受的内容类型:文本/html使用AFNetworking 2.0
- 缺少推荐的图标文件-该包不包含iPhone / iPod Touch的应用程序图标,像素为“120x120”,png格式