ios - 具有自动更新当前时区的静态让日历不起作用

标签 ios swift static calendar timezone

在我的应用程序中,我在 SharedCalendar 类中有一个静态的 gregorian 属性,其定义如下:

static let gregorian: Calendar = {
    var calendar = Foundation.Calendar(identifier: .gregorian)
    calendar.timeZone = TimeZone.autoupdatingCurrent
    return calendar
}()

当我想访问特定时区中某个日期的某一天时,我会调用:

SharedCalendar.gregorian.dateComponents([ .day ], from: someDate).day!

假设 someDateDate(timeIntervalSinceReferenceDate: 512658000.0)2017-03-31 13:00:00 +0000

当我在温哥华时区启动应用程序时,SharedCalendar.gregorian.timeZone 属性具有值 America/Vancouver (autoupdatingCurrent)SharedCalendar 的结果。 gregorian.dateComponents([ .day ], from: someDate).day!31 这是正确的

当我将应用程序置于后台并将时区切换到悉尼并再次运行应用程序时,SharedCalendar.gregorian.timeZone 属性具有值 Australia/Sydney (autoupdatingCurrent)(这是正确的),但是 SharedCalendar.gregorian.dateComponents([ .day ], from: someDate).day! 的结果是 31 错误(应为 1)

当我将 gregorian 属性的定义更改为 var 时:

var gregorian: Calendar {
    var calendar = Foundation.Calendar(identifier: .gregorian)
    calendar.timeZone = TimeZone.autoupdatingCurrent
    return calendar
}

一切正常,对于 America/Vancouver (autoupdatingCurrent) 我得到 31,对于 Australia/Sydney (autoupdatingCurrent) 我得到 1

现在我不太明白 TimeZone.autoupdatingCurrent 是如何工作的。当设备的时区发生变化时,SharedCalendar.gregorian.timeZone 反射(reflect)了设备的时区,但看起来 SharedCalendar.gregorian 以某种方式使用旧时区。

有人对这种行为有解释吗?

最佳答案

我报告了radar关于这个问题,今天 Apple 回应:

The reason that your static let calendar’s time zone doesn’t update is that you need to issue a call to NSTimeZone.resetSystemTimeZone() to sync up with the system time zone. See the documentation for NSTimeZone.resetSystemTimeZone() for more info: https://developer.apple.com/documentation/foundation/nstimezone/1387189-resetsystemtimezone?language=objc

The reason your var calendar works is because every call to the calendar property actually creates a new computed calendar, which happens to be set to a new time zone representing the current system time zone.

这是有道理的,因为 static let 缓存了系统的时区,并且从 NSTimeZone.resetSystemTimeZone 的文档中我们可以读到:

If the application has cached the system time zone, this method clears that cached object. If you subsequently invoke systemTimeZone, NSTimeZone will attempt to redetermine the system time zone and a new object will be created and cached (see systemTimeZone).

关于ios - 具有自动更新当前时区的静态让日历不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44190763/

相关文章:

java - 如何在java中的for循环中将计算保存在同一变量中

ios - 数组 : Swift and IOS

ios - iOS 的 ScrollView 中缺少 TextInput,但 Android 中没有

ios - Apple 的 TestFlight 和证书

xcode - MacOS swiftui NSLayoutConstraint 调整错误对象的大小

PHP 调用静态函数

ios - NSInternalInconsistencyException : 'Invalid parameter not satisfying: !stayUp || CLClientIsBackgroundable(internal->fClient)'

ios - 如何从 View 中完全关闭 uialertcontroller?

ios - 向 UITableViewController 内的表格 View 添加左右边距

c++ - 为什么在定义(而不是声明)静态数据成员时不能使用 "' static'?