How to support NSCalendar with both iOS 7 and 8?

戏子无情 提交于 2019-12-18 12:54:50

问题


iOS 8 introduced some new values for old methods. For instance, creating a calendar used to be like this:

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

Now, the calendar identifier has changed and I should create the object like so:

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

Thing is, the compiler warns me only in the first situation that NSGregorianCalendar is deprecated. However, The compiler doesn't warn me at all about NSCalendarIdentifierGregorian compatibility with iOS 7.
Does it mean that NSCalendarIdentifierGregorian works under iOS 7 either?
If not, what's the best way of creating a calendar with a calendar identifier depending on the OS? checking OS version every single time seems tedious.

Thank you.


回答1:


You can use the built-in __IPHONE_8_0 macro, coupled with custom defines.

Your custom defines will simply refer to the underlying value defined in Objective-C. Since these are convenience defines that are widely used, I stick them into a header file, and include that in my PCH file (in Xcode 6, you have to create the pre-compiler header yourself, and point to it in your build settings).

When iOS 9 is released, you will still be able to use __IPHONE_8_0 without updating, since it will still be defined, for all versions after iOS 8.

In a header file (or Precompiler Header - project_name.pch)

#ifdef __IPHONE_8_0
    #define GregorianCalendar NSCalendarIdentifierGregorian
#else
    #define GregorianCalendar NSGregorianCalendar
#endif

In your implementation files

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:GregorianCalendar];



回答2:


I know you asked about Gregorian specifically, but would it not always be preferable anyway to use:

NSCalendar *calendar = [NSCalendar currentCalendar];


来源:https://stackoverflow.com/questions/25626823/how-to-support-nscalendar-with-both-ios-7-and-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!