【问题标题】:How to make a if statement with NSNull in objective-c如何在objective-c中使用NSNull进行if语句
【发布时间】:2011-09-26 06:32:49
【问题描述】:

我正在开发一个 iPhone 应用程序,其中我需要使用JSON 来接收来自服务器的数据。 在iPhone端,我将数据转换成NSMutableDictionary

但是,有一个日期类型的数据是空的。

我用下面这句话来读日期。

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

if (arriveTime) {
    job.arriveDone = [NSDate dateWithTimeIntervalSince1970:[arriveTime intValue]/1000];
}

当到达时间为空时,我如何进行 if 语句。我试过[arriveTime length] != 0,但是我不起作用,因为arriveTime是一个NSNull,没有这个方法。

【问题讨论】:

    标签: iphone json nsmutabledictionary nsnull


    【解决方案1】:

    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); }
    

    或者,如果您觉得更清楚,您可以使用isKindOfClass:

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

    【讨论】:

      【解决方案2】:

      一行

      arriveTime ? job.arriveDone = [NSDate dateWithTimeIntervalSince1970:[arriveTime intValue]/1000]; : NSLog(@"Arrive time is not yet scheduled");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-08
        • 2010-12-05
        • 2015-03-01
        • 1970-01-01
        • 2021-10-26
        • 1970-01-01
        相关资源
        最近更新 更多