如何在objective-c中使用NSNull创建if语句

Fan*_* Wu 16 iphone json nsmutabledictionary nsnull

我正在开发一个iPhone应用程序,我需要使用JSON它从服务器接收数据.在iPhone方面,我将数据转换为NSMutableDictionary.

但是,日期类型数据为空.

我用下面的句子来读日期.

NSString *arriveTime = [taskDic objectForKey:@"arriveTime"];
NSLog(@"%@", arriveTime);

if (arriveTime) {
    job.arriveDone = [NSDate dateWithTimeIntervalSince1970:[arriveTime intValue]/1000];
}
Run Code Online (Sandbox Code Playgroud)

当arrivalTime为null时,如何创建if语句.我试过[到达时间长度]!= 0,但我不工作,因为arriTime是一个NSNull并且没有这个方法.

jus*_*tin 38

NSNull实例是一个单例.您可以使用简单的指针比较来完成此任务:

if (arriveTime == nil) { NSLog(@"it's nil"); }
else if (arriveTime == (id)[NSNull null]) { // << the magic bit!
  NSLog(@"it's NSNull");
}
else { NSLog(@"it's %@", arriveTime); }
Run Code Online (Sandbox Code Playgroud)

或者,isKindOfClass:如果您发现更清楚,您可以使用:

if (arriveTime == nil) { NSLog(@"it's nil"); }
else if ([arriveTime isKindOfClass:[NSNull class]]) {
  ...
Run Code Online (Sandbox Code Playgroud)