简体   繁体   中英

NSDateFormatter return (null) string when NSDate is nil

I use date formatter to get new string, but in some cases startDate can be nil.

resultDate = [NSString stringWithFormat:@"%@", [formatter stringFromDate:startDate]];

And then resultDate get (null) string (NSTaggedPointerString), but I expect to get just nil in case if formatter get nil as a parameter of date.

The currently accepted answer isn't actually right.

stringFromDate does return nil when you pass it a nil date.

The reason your string is "(null)" is because [NSString stringWithFormat:"%@", nil] returns the string "(null)"

The stringFromDate instance method on NSDateFormatter is expecting a (nonnull NSDate *) and returns NSString * _Nonnull .

The _Nonnull keyword specifies that stringFromDate will always return an NSString * and never return nil, so on a nil date stringFromDate will return the string "null" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM