سؤال

In our app we're using an NSCalendar to process NSDate objects, for example to obtain the day component.

This NSCalendar instance is a singleton object because we do tons of date calculations in a short amount of time and we noticed that creating new instances with [[NSCalendar alloc] initWith...] each time we needed it was consuming too much time.

The problem is, that if you keep an NSCalendar instance throughout the application execution time, this instance keeps the timezone property unchanged, even if the timezone changed.

So, the problem is that we want to detect changes to the timezone and react properly by either:

self.singletonCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]

or

self.singletonCalendar.timezone = [NSTimezone localTimezone];

Possible solutions we're discussing:

  1. Update the timezone property each time the application becomes active.
  2. Use KVO to detect timezone changes (tried this without success).

Thanks, Nicolás.


Implemented proposed solution by Putz1103:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(significantTimeChangeNotification) name:UIApplicationSignificantTimeChangeNotification object:nil];

- (void)significantTimeChangeNotification
{
    NSTimeZone *localTimezone = [NSTimeZone localTimeZone];
    [KIDateUtils setCalendarTimezone:localTimezone];
}
هل كانت مفيدة؟

المحلول

I would do a mashup of two options. I would update it on app start (or entering foreground). But for while the app is currently in the foreground you can set a listener for time changes like the answer here:

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

نصائح أخرى

Have your singleton register for the UIApplicationSignificantTimeChangeNotification notification. When this is received, update the NSCalendar instance in your singleton.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top