【问题标题】:How to compare NSString with NSString nil Value? [duplicate]如何比较 NSString 和 NSString nil 值? [复制]
【发布时间】:2015-01-19 06:29:01
【问题描述】:
我是 iOS 开发新手。当我将NSString 与NSString nil 值进行比较时出现错误。它在 if 条件下不起作用。
我的代码是:
NSDictionary *responseFromJSON = [JSON objectForKey:@"response"];
NSString *strResponseMsg = [responseFromJSON objectForKey:@"104"];
if ([strResponseMsg isEqualToString:nil])
{
NSLog(@"login Invalid");
}
else
{
NSLog(@"login success");
}
【问题讨论】:
标签:
ios
objective-c
iphone
if-statement
ios7
【解决方案1】:
你可以这样做,
NSString * string = nil;
if (string!=nil && // not nil, means 0x0 object
string.length>0 && // at leaset one character should exists
[string isEqual:[NSNull null]]) { // to avoid 'null' in string
// valid string
}
【解决方案2】:
你可以这样做,
if ([yourString isEqual:[NSNull null]])
{
//your code goes here
}
希望这会有所帮助。
【解决方案3】:
在下面使用
NSString *strResponseMsg = [responseFromJSON objectForKey:@"104"];
if (!strResponseMsg)
{
NSLog(@"login Invalid");
}
else
{
NSLog(@"login success");
}
【解决方案4】:
如果你想检查 NSString 是 nil 还是空。
你只需要这样做:
if (strResponseMsg.length) {}
因为如果 strResponseMsg 为 nil 或为空,它不会进入内部。它只会在 strResponseMsg 不为 nil 且不为空时进入。