首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检测[NSTimeZone localTimezone] secondsFromGMT属性更改

检测[NSTimeZone localTimezone] secondsFromGMT属性更改
EN

Stack Overflow用户
提问于 2014-01-23 15:34:24
回答 2查看 560关注 0票数 0

在我们的应用程序中,我们使用NSCalendar来处理NSDate对象,例如获取day组件。

这个NSCalendar实例是一个单例对象,因为我们在短时间内进行了大量的日期计算,我们注意到使用[NSCalendar alloc initWith.]创建新实例每次我们需要的时候,都会花费太多的时间。

问题是,如果在整个应用程序执行期间保持一个NSCalendar实例,则此实例将保持时区属性不变,即使时区发生了更改。

因此,问题在于,我们希望检测时区的变化,并通过以下两种方法作出适当的反应:

代码语言:javascript
复制
self.singletonCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]

代码语言:javascript
复制
self.singletonCalendar.timezone = [NSTimezone localTimezone];

我们正在讨论的可能的解决办法:

  1. 每次应用程序活动时更新时区属性。
  2. 使用KVO检测时区更改(尝试过,但没有成功)。

谢谢尼可拉斯。

通过Putz1103实现了拟议的解决方案:

代码语言:javascript
复制
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(significantTimeChangeNotification) name:UIApplicationSignificantTimeChangeNotification object:nil];

- (void)significantTimeChangeNotification
{
    NSTimeZone *localTimezone = [NSTimeZone localTimeZone];
    [KIDateUtils setCalendarTimezone:localTimezone];
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-01-23 15:39:35

我会做两个选项的混搭。我会更新它在应用程序启动(或进入前台)。但是,当应用程序当前处于前台时,您可以为时间的变化设置一个监听器,比如answer here

"UIApplicationDelegate" has a method called "applicationSignificantTimeChange:" that gets called when there is a significant change in the time.

票数 2
EN

Stack Overflow用户

发布于 2014-01-23 15:41:49

让您的单例寄存器用于UIApplicationSignificantTimeChangeNotification通知。当收到此信息时,更新单例中的NSCalendar实例。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21312651

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档