Search code examples
iosobjective-cnsdateformatterunrecognized-selector

NSDateFormatter dateFromString on null Values


When I try to convert a string into a date using the NSDateFormatter dateFromString method, the app crashes on Null values. I have found lots of answers and discussions on SO of when dateFromString returns null but can't find anything on how to handle a null value input.

The string in question is parsed from JSON coming from a server and is empty a fair amount of the time. Following code works if date time has a value but crashes on null values saying: 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);

Thanks for any suggestions.


Solution

  • You need to check to see if starttimestr is really a string or not:

    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`).
    }