如何在Objective-C中测试NSString是否为空?
当前回答
这对我来说是一种魅力
如果NSString是s
if ([s isKindOfClass:[NSNull class]] || s == nil || [s isEqualToString:@""]) {
NSLog(@"s is empty");
} else {
NSLog(@"s containing %@", s);
}
其他回答
你有两个方法来检查字符串是否为空:
让我们假设你的字符串名字是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
}
选择上述任何一种方法,了解字符串是否为空。
马克的回答是正确的。但我想借此机会引用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);
}
另一个选项是用isEqualToString检查它是否等于@"":如下所示:
if ([myString isEqualToString:@""]) {
NSLog(@"myString IS empty!");
} else {
NSLog(@"myString IS NOT empty, it is: %@", myString);
}
只需使用一个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
}
在任何情况下,最好的方法是检查给定字符串的长度。如果你的字符串是myString,那么代码是:
int len = [myString length];
if(len == 0){
NSLog(@"String is empty");
}
else{
NSLog(@"String is : %@", myString);
}
推荐文章
- Xcode构建失败“架构x86_64未定义的符号”
- 如何使用Xcode创建。ipa文件?
- 动态改变UILabel的字体大小
- registerForRemoteNotificationTypes: iOS 8.0及以上版本不支持
- 新的自动引用计数机制是如何工作的?
- 如何测试对象在Objective-C中的类?
- 在iPhone上确定用户是否启用了推送通知
- 是否有可能禁用浮动头在UITableView与UITableViewStylePlain?
- 从Cocoa应用程序执行一个终端命令
- 错误ITMS-9000:“冗余二进制文件上传。火车1.0版本已经有一个二进制版本上传。
- Swift -转换为绝对值
- Swift编译器错误:“框架模块内的非模块化头”
- 从父iOS访问容器视图控制器
- 自定义dealloc和ARC (Objective-C)
- 调整UITableView的大小以适应内容