When does dateByAddingComponents:toDate:options return nil?

前端 未结 1 1305
陌清茗
陌清茗 2021-02-07 10:57

I\'ve been using dateByAddingComponents:toDate:options: and dateByAddingUnit:value:toDate:options: and using optional binding to get the date out of it

1条回答
  •  伪装坚强ぢ
    2021-02-07 11:20

    In practice, if you're just adding a month to a date, you will not get nil values.

    You can, though, get a nil value in some degenerate situations. For example, if you are using Islamic calendar and add -9,999,999 years, you'll get a nil (though, curiously, not in other calendars). Other calendars will often overflow/wrap the year in these extreme situations (even though you'd expect them to return nil, given the documentation you quote).

    Personally, I suspect there are currently very few situations in which you'll get nil values. I tried all sorts of extreme values and the Islamic calendar was the only one that I succeeded in getting a nil value. The doesn't mean, though, that Apple might not add more robust date validation logic in the future. We'd probably have to get counsel from Apple (or see the source code for NSCalendar) to answer this question definitively.

    So, bottom line, I'd suggest keeping your guard statement, but it's unlikely to fail in real-world scenarios.

    0 讨论(0)
提交回复
热议问题