Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to support NSCalendar with both iOS 7 and 8?

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.

like image 901
Noam Solovechick Avatar asked Sep 02 '14 15:09

Noam Solovechick


2 Answers

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];
like image 100
Sheamus Avatar answered Nov 20 '22 21:11

Sheamus


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

NSCalendar *calendar = [NSCalendar currentCalendar];
like image 2
RegularExpression Avatar answered Nov 20 '22 22:11

RegularExpression