空值上的 NSDateFormatter dateFromString

NSDateFormatter dateFromString on null Values

当我尝试使用 NSDateFormatter dateFromString 方法将字符串转换为日期时,应用程序因 Null 值而崩溃。我找到了很多关于 dateFromString returns null 时的答案和讨论,但找不到有关如何处理空值输入的任何内容。

有问题的字符串是从来自服务器的 JSON 中解析出来的,并且在相当长的时间内是空的。如果日期时间有值但在空值时崩溃,则以下代码有效:NSNull length]: unrecognized selector sent to instance 0x39ab2a70

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *starttimestr = feedElement[@"starttime"];
NSLog(@"starttimestr%@",starttimestr);
NSDate *starttime = [dateFormatter dateFromString:starttimestr];
NSLog(@"starttime%@",starttime);

感谢您的任何建议。

您需要检查 starttimestr 是否真的是一个字符串:

NSString *starttimestr = feedElement[@"starttime"];
if ([starttimestr isKindOfClass:[NSString class]]) {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSLog(@"starttimestr%@",starttimestr);
    NSDate *starttime = [dateFormatter dateFromString:starttimestr];
    NSLog(@"starttime%@",starttime);
} else {
    // starttimestr is either `nil` or something other than `NSString` (such as `NSNull`).
}