rangeOfUnit returns `NSNotFound` 一个月中的几周(iOS7 错误)

rangeOfUnit returns `NSNotFound` for weeks in month (iOS7 bug)

您好,我对 NSCalendar 中的 rangeOfUnit() 方法有疑问。我得到 NSNotFound 值,而我期望值在 <4,6> 范围内(一个月中的周数)。真正让我担心的是它依赖于平台(不适用于 iOS7)。该错误是在我调查 CVCalendar 组件时发现的。我在我的 iPhone 4S 上设置了英语和公历 iOS 7.1.1.

// Range of the month.
let range = calendar.rangeOfUnit(NSCalendarUnit.WeekOfMonth, inUnit: NSCalendarUnit.Month, forDate: date)
// Should return values in range <4,6>
print("Range \(range)")
let range2 = calendar.rangeOfUnit(NSCalendarUnit.Month, inUnit: NSCalendarUnit.WeekOfMonth, forDate: date)
// Invalid range. No week contains no months.
print("Range \(range2)")
let range3 = calendar.rangeOfUnit(NSCalendarUnit.Weekday, inUnit: NSCalendarUnit.Month, forDate: date)
print("Range \(range3)")

控制台上的打印日期:

po date
2015-11-17 10:05:39 +0000

iOS9 模拟器和其他非iOS7 设备上的控制台输出:

Range (1,5)
Range (2147483647,2147483647)
Range (1,7)

iOS7 设备上的控制台输出:

Range (2147483647,2147483647)
Range (2147483647,2147483647)
Range (1,7)

您可以在 Swift 2.

中使用可用性检查
let weekOfMonthUnit: NSCalendarUnit
if #available(iOS 8, *) {
    weekOfMonthUnit = NSCalendarUnit.WeekOfMonth
} else {
    weekOfMonthUnit = NSCalendarUnit.NSWeekCalendarUnit
}
let range = calendar.rangeOfUnit(weekOfMonthUnit, inUnit: NSCalendarUnit.Month, forDate: date)
print("Range \(range)")