2015-05-02 33 views
0

定時器將23小時,格式爲00:00:00(小時:分:秒),所以當按下按鈕時,定時器將開始倒計時23小時,我希望這是由NSUserDefaults保存,以便每當我退出應用程序或切換到另一個視圖控制器時,剩餘時間仍然存在。NSTimer和NSUserDefaults

在h。

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; 
NSDate *now = [NSDate date]; 
double countDown = 82800.0; // in seconds, get this from your counter 
[userDefaults setObject:now forKey:@"timeAtQuit"]; 
[userDefaults setDouble:countDown forKey:@"countDown"]; 
[userDefaults synchronize]; 


// restore state 
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; 
NSDate *timeAtQuit = [userDefaults objectForKey:@"timeAtQuit"]; 
double timeSinceQuit = [timeAtQuit timeIntervalSinceNow]; 
double countDown = timeSinceQuit + [userDefaults doubleForKey:@"countDown"]; 

誰能告訴我如何將NSUserDefault有機結合起來:單位爲m:

-(void) timerRun { 

    secondCount = secondCount - 1; 
    int hours = (secondCount/ 3600) % 24; 
    int minuts = (secondCount/60) % 60; 
    int seconds = secondCount % 60; 


    NSString *timerOutput = [NSString stringWithFormat:@"%2d:%.2d:%2d", hours, minuts, seconds]; 

    countdownLabel.text = timerOutput; 

} 


-(void) setTimer { 

    secondCount = 82800; 
    countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerRun) userInfo:nil repeats:YES]; 


} 


- (IBAction)start:(id)sender { 

    [self setTimer]; 


} 

這裏定時器

@interface ViewController : UIViewController { 

    IBOutlet UILabel *countdownLabel; 
    NSTimer *countdownTimer; 
    int secondCount; 
} 

- (IBAction)start:(id)sender; 

代碼是相關的NSUserDefaults的代碼定時器以及代碼的放置位置,以便計時器在退出ap後可以運行摺疊或去另一個視圖控制器

請幫助

回答

0

根據你的解釋,我明白,你的計時器對象應保持均勻的工作,當你負責顯示時間視圖控制器尚未初始化,所以當應用第二次啓動時,視圖控制器將從計時器實例中獲得正確的剩餘時間。因此,我建議您創建一個單獨的類,以跟蹤應用程序的狀態(通過NSNotificationCenter類)並處理定時器對象的重新初始化或失效。

這裏是概念設計的描述上面的邏輯證明:

TimerManager.h

extern NSString * const TimerManagerDidCountDownNotification; 

@interface TimerManager 
@property (nonatomic, strong, readonly) NSTimer *timer; 
@property (nonatomic, assign, readonly) CGFloat remainingTime; 

+ (instancetype)sharedManager; 
- (void)setCountDown:(CGFloat)countDown override:(BOOL)override; 
@end 

TimerManager.h

NSString * const TimerManagerDidCountDownNotification = @"TimerManagerDidCountDownNotification"; 

@interface TimerManager() 
@property (nonatomic, strong, readwrite) NSTimer *timer; 
@property (nonatomic, assign, readwrite) CGFloat remainingTime; 
@end 

@implementation TimerManager 
@synthesize remainingTime=_remainingTime; 

- (instancetype)init 
{ 
    self = [super init]; 

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil]; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil]; 

    return self; 
} 

+ (instancetype)sharedManager 
{ 
    static TimerManager *sharedManager = nil; 
    static dispatch_once_t onceToken; 

    dispatch_once(&onceToken, ^{ 
     sharedManager = [[self alloc] init]; 
    }); 

    return sharedManager; 
} 

- (void)didCountDown 
{ 
    if (self.remainingTime > 0.0) { 
     CGFloat newRemainingTime = self.remainingTime - 1.0; 
     [[NSNotificationCenter defaultCenter] postNotificationName:TimerManagerDidCountDownNotification object:nil userInfo:@{"remainingTime": @(newRemainingTime)}]; 
     self.remainingTime = newRemainingTime; 
    } 
    else { 
     [_timer invalidate]; 
     _timer = nil; 
     [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"remaining_time"]; 
     [[NSUserDefaults standardUserDefaults] synchronize]; 
    } 
} 

- (CGFloat)remainingTime 
{ 
    return [[NSUserDefaults standardUserDefaults] floatForKey:@"remaining_time"]; 
} 

- (CGFloat)setRemainingTime:(CGFloat)remainingTime 
{ 
    [[NSUserDefaults standardUserDefaults] setFloat:remainingTime forKey:@"remaining_time"]; 
    [[NSUserDefaults standardUserDefaults] synchronize]; 
} 

- (void)setCountDown:(CGFloat)countDown override:(BOOL)override 
    if (override || self.remainingTime == 0.0) { 
     [_timer invalidate]; 
     self.remainingTime = countDown; 
     _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(didCountDown) userInfo:nil repeats:YES]; 
    } 
} 

- (void)applicationDidEnterBackground:(NSNotification *)notification 
{ 
    if (_timer) { 
     [_timer invalidate]; 
     _timer = nil; 
    }  
} 

- (void)applicationWillEnterForeground:(NSNotification *)notification 
{ 
    if (!_timer) { 
     _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(didCountDown) userInfo:nil repeats:YES]; 
    } 
} 

- (void)dealloc 
{ 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
} 

在您的視圖控制器類,你可以覆蓋viewDidLoad並註冊您的回調函數(timerRun:)到通知中心對象,以從定時器獲得剩餘時間:

ViewController.m

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(timerRun:) name:TimerManagerDidCountDownNotification object:nil]; 
} 

- (void)timerRun:(NSNotification *)notification 
{ 
    CGFloat secondCount = [notification[@"remainingTime"] floatValue]; 
    int hours = (secondCount/3600) % 24; 
    int minuts = (secondCount/60) % 60; 
    int seconds = secondCount % 60; 

    NSString *timerOutput = [NSString stringWithFormat:@"%2d:%.2d:%2d", hours, minuts, seconds]; 

    countdownLabel.text = timerOutput; 
} 

- (IBAction)start:(id)sender 
{ 
    [[TimerManager sharedManager setCountDown:82800.0 override:YES]; 
} 

- (void)dealloc 
{ 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
} 

您可以使用application:didFinishLaunchingWithOptions方法爲出發點,以觸發與給定值countdown你的計時器。

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    // some other initialization logic here... 

    [[TimerManager sharedManager] setCountDown:82800.0 override:NO]; 
    return YES; 
} 
+0

我很抱歉,我不明白你的代碼 – Katie

+0

你必須有標籤和按鈕作爲觸發櫃檯上一個更簡單的方法,並且能夠節省it @ozgur – Katie

+0

然而,我確信有更簡單的方法,總是最好將應用程序中的不同功能保留在彼此之外,以便您的代碼更具可讀性和可理解性。 – ozgur