2014-01-06 2 views
0

NSTimer에 시작에서 중지로 텍스트를 변경하는 UIButton이있는 방법은 무엇입니까? 또한 다른 UIButton이 타이머를 일시 중지하기 위해 추가됩니다. 그래서 시작을 누르면 시간, 분, 초 단위로 레이블에 타이머가 표시됩니다. 타이머가 실행되는 동안 타이머를 일시 중지하는 방법이 있습니까 (NSUserDefaults를 사용해야 함). 또한 시작 단추를 누른 시간을 저장 한 다음 단추를 다시 눌렀다가 멈추는 시간을 절약 할 수있는 방법이 있습니까? 또한 일시 중지 버튼을 눌러 타이머를 일시 중지하고 일시 중지를 다시 누르면 타이머가 다시 시작됩니까?NSTimer with NSUserDefaults

+3

이것은 매우 기본적인 것입니다. 당신은 정말로 펀더멘탈을 재검토해야합니다. 그런 식으로 자신 만의 문제를 해결할 수 있습니다. 다른 사람들이 그렇게하기를 기다리는 두통입니다. – pasawaya

+0

@ user3121577 qegal이 맞습니다. Xcode에서 정말 쉽지만 게시물에 글을 쓰고 싶습니다. 시도해보고 관리하지 않으면 다시 돌아 오십시오 :) –

+0

지금까지 타이머와 물건이 있지만 시작 시간과 종료 시간을 저장하고 타이머를 일시 중지하는 방법을 모르겠습니다. – Ed3121577

답변

0

당신이 NSDate 객체 startTimestopTime

[[NSUserDefaults standardUserDefaults] setObject:startTime forKey:@"startTime"]; 
[[NSUserDefaults standardUserDefaults] setObject:stopTime forKey:@"stopTime"]; 

이 아니면 수레 startTimefstopTimef

[[NSUserDefaults standardUserDefaults] setFloat:startTimef forKey:@"startTime"]; 
[[NSUserDefaults standardUserDefaults] setFloat:stopTimef forKey:@"stopTime"]; 

체크 아웃 NSUserDefaults docs을 사용할 수 있습니다 가정.

다음은 위대한 set of tutorials입니다.

+0

오브젝트와 플로트의 차이점은 무엇입니까? 미안, 초보자입니다 – Ed3121577

+0

음, float는 원시 데이터 유형 중 하나입니다. 기본적인 프로그래밍 개념을 익히려면 튜토리얼부터 시작해야합니다. http://www.raywenderlich.com/tutorials –

2

일시 중지를 지원하지 않는 타이머가 필요한 경우 경과 한 시간을 계산할 수 있도록 타이머가 시작된 NSDate을 알아야합니다.

- (void)startTimer 
{ 
    self.timerStartDate = [NSDate date]; 
} 

귀하의 NSTimer는 시간을 추적하는 것이 아니라 주기적으로 라벨을 업데이트 :

@property (strong, nonatomic) NSDate *timerStartDate; 

버튼을 탭하면 : 인스턴스 변수를 만듭니다. 당신은 타이머가 마지막으로 시작한 이후 경과 된 시간을 계산하는 외에, 타이머를 일시 정지 할 수 있도록하려면, 그러나 당신을

- (void)startTimer 
{ 
    self.timerStartDate = [NSDate date]; 

    // start timer to update label 
    if (!self.labelUpdateTimer) { 
     self.labelUpdateTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 
                 target:self 
                selector:@selector(updateLabel) 
                userInfo:nil 
                repeats:YES]; 
    } 
} 

- (void)updateLabel 
{ 
    NSTimeInterval secondsElapsedSinceTimerStart = 0; 
    if (self.timerStartDate) { 
     secondsElapsedSinceTimerStart = [[NSDate date] timeIntervalSinceDate:self.timerStartDate]; 
    } 

    NSString *formattedTime = <format time elapsed the way you like>; 
    self.label.text = formattedTime; 
} 

- (void)dealloc 
{ 
    // make sure timer is not firing anymore! 
    if (_labelUpdateTimer) { 
     [_labelUpdateTimer invalidate]; 
     _labelUpdateTimer = nil; 
    } 
} 

다음 -startTimer 방법을

@property (strong, nonatomic) NSTimer *labelUpdateTimer; 

및 업데이트 : 인스턴스 변수를 만듭니다 이전에 경과 한 시간을 저장해야합니다 (이전에 타이머를 시작/일시 중지 한 경우). 타이머

@property (nonatomic) NSTimeInterval previouslyElapsedSeconds; 

그리고 때 일시 :

- (void)pauseTimer 
{ 
    // update elapsedSeconds 
    if (self.timerStartDate) { 
     self.previouslyElapsedSeconds += [[NSDate date] timeIntervalSinceDate:self.timerStartDate]; 
     self.timerStartDate = nil; 
    } 

    [self.labelUpdateTimer invalidate]; 
    self.labelUpdateTimer = nil; 
} 

업데이트 -updateLabel을 : 인스턴스 변수를 만듭니다

- (void)updateLabel 
{ 
    NSTimeInterval secondsElapsedSinceTimerStart = 0; 
    if (self.timerStartDate) { 
     secondsElapsedSinceTimerStart = [[NSDate date] timeIntervalSinceDate:self.timerStartDate]; 
    } 

    // account for previously elapsed time 
    NSTimeInterval totalSecondsElapsed = self.previouslyElapsedSeconds + secondsElapsedSinceTimerStart; 

    NSString *formattedTime = <format time elapsed the way you like>; 
    self.label.text = formattedTime; 
} 
이 경우에도 타이밍을 유지하려는 경우

NSUserDefaults 에만 필요합니다 응용 프로그램이 종료됩니다 (그냥 배경이 아니라). 이 경우 인스턴스 변수 대신 NSUserDefaults에 previouslyElapsedSecondstimerStartDate을 저장하십시오.

+0

응용 프로그램이 백그라운드를 실행하는 경우에도 여전히 NSUserDeafaults가 있습니까? – Ed3121577

+0

다른 프로세스의 메모리를 정리하기 위해 시스템을 종료해야하는 경우가 아니라면 NSUserDefaults가 필요하지 않으므로 인스턴스 변수가 해제됩니다. 그러나 앱을 다시 시작한 후 (사용자 또는 시스템에 의해) 앱이 종료 될 가능성이 있습니다. 타이밍이 그 다음에 계속되어야하는지 여부는 귀하의 요청입니다. 그렇다면 그 값을 NSUserDefaults에 저장해야합니다. –