Am uitat sa pun aici inca 3-4 metode:
In app delegate implementarea timer-ului si a metodei care este executata la fiecare secunda:
- (void)applicationDidBecomeActive:(UIApplication *)application
{
NSLog(@"%@",NSStringFromSelector(_cmd));
self.myTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self selector: @selector(timerMethod:) userInfo: nil repeats: YES];
}
- (void)applicationWillResignActive:(UIApplication *)application
{
NSLog(@"%@",NSStringFromSelector(_cmd));
if([self.myTimer isValid])
[self.myTimer invalidate];
[[NSUserDefaults standardUserDefaults] setInteger: self.rootTimerValue forKey: @"self.rootTimerValue"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void) timerMethod: (NSTimer *) theTimer
{
if(self.rootTimerValue > 0)
self.rootTimerValue--;
else
{
// MAKE 1 TOKEN AVAILABLE
int tokens = [[NSUserDefaults standardUserDefaults] integerForKey: @"tokens"];
NSLog(@"tokens %d",tokens);
tokens++;
[[NSUserDefaults standardUserDefaults] setInteger: tokens forKey: @"tokens"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"tokens %d",tokens);
self.rootTimerValue = 1800;
}
}
In controller-ul de game over unde afisez timer-ul se apeleaza urmatoarea metoda de fiecare data cand valoarea variabilei “rootTimerValue” din app delegate este modificata
#pragma mark NSKeyValueObservingProtocol method
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if([keyPath isEqualToString: @"rootTimerValue"])
{
NSNumber *theValue = [change objectForKey: NSKeyValueChangeNewKey];
int value = [theValue intValue];
int minute = value / 60;
int secunde = value % 60;
if(self.view.superview != nil)
self.getTokensTimerLabel.text = [NSString stringWithFormat: @"%.2d:%.2d",minute,secunde];
}
}
Sper sa va fie de folos daca aveti nevoie de asa ceva