如何使用iOS 7和8支持NSCalendar?

Noa*_*ick 16 objective-c ios ios8

iOS 8为旧方法引入了一些新值.例如,创建日历曾经是这样的:

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
Run Code Online (Sandbox Code Playgroud)

现在,日历标识符已更改,我应该像这样创建对象:

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
Run Code Online (Sandbox Code Playgroud)

事情是,编译器只在第一种情况下警告我不推荐使用NSGregorianCalendar.但是,编译器并没有警告我NSCalendarIdentifierGregorian与iOS 7的兼容性.这
是否意味着NSCalendarIdentifierGregorian在iOS 7下工作?
如果没有,根据操作系统创建带日历标识符的日历的最佳方法是什么?每次检查操作系统版本似乎很乏味.

谢谢.

She*_*mus 31

您可以使用内置__IPHONE_8_0宏,再加上自定义定义.

您的自定义定义将仅引用Objective-C中定义的基础值.由于这些是广泛使用的便利定义,我将它们粘贴到头文件中,并将其包含在我的PCH文件中(在Xcode 6中,您必须自己创建预编译器头,并在构建设置中指向它) .

当iOS 9发布时,您仍然可以在__IPHONE_8_0不更新的情况下使用,因为它仍将被定义,适用于iOS 8之后的所有版本.

在头文件(或预编译器头 - project_name.pch)中

#ifdef __IPHONE_8_0
    #define GregorianCalendar NSCalendarIdentifierGregorian
#else
    #define GregorianCalendar NSGregorianCalendar
#endif
Run Code Online (Sandbox Code Playgroud)

在您的实现文件中

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:GregorianCalendar];
Run Code Online (Sandbox Code Playgroud)