2011-04-15 62 views
1

我在視圖控制器中顯示10個問題。我想計算回答這些問題所花費的時間。我想在時間達到零後設置時間倒計時的方式我想要顯示警報。請幫幫我。如何在iphone sdk中設置NSTimer?

在此先感謝。

回答

4

你似乎想要2件事。

一個逝去的問題的開始之間的時間,直到它得到答案,你可以做到這一點:

NSDate *now = [NSDate date]; 
NSTimeInterval *elapsedTime = [now timeIntervalSinceNow]; 

參考: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html

二是使用NSTimer進行倒計時。你可以用下面的代碼做到這一點:

NSTimer *theTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countdownTracker:) userInfo:nil repeats:YES]; 
// Assume a there's a property timer that will retain the created timer for future reference. 
self.timer = theTimer; 
// Assume there's a property counter that track the number of seconds before count down reach. 
self.counter = 10; 

將由計時器調用的方法。

- (void)countdownTracker:(NSTimer *)theTimer { 
    self.counter--; 
    if (self.counter < 0) { 
     [self.timer invalidate]; 
     self.timer = nil; 
     self.counter = 0; 
     [[[[UIAlertView alloc] initWithTitle:@"Countdown" message:@"Countdown completed." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease] show]; 
    } 
} 

這應該有效。

參考: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/Reference/NSTimer.html

+0

將它在後臺運行? – UserDev 2014-01-24 14:03:15

1
- (void) showClock 
{ 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateStyle:NSDateFormatterNoStyle]; 
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle]; 
    [dateFormatter setDateFormat:@"HH"]; 
    int hour = [[dateFormatter stringFromDate:[NSDate date]] intValue]; 
    [dateFormatter setDateFormat:@"mm"]; 
    int minute = [[dateFormatter stringFromDate:[NSDate date]] intValue]; 
    [dateFormatter release]; 
    NSTimeInterval remainingSec = [databaseDate timeIntervalSinceNow]; 
    if (remainingSec >= 0) 
    { 
     timer = nil; 

     self.databaseDate = [NSDate dateWithTimeIntervalSinceNow:0]; 
     remainingSec = [databaseDate timeIntervalSinceNow]; 
     timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self 
         selector:@selector(showClock) 
         userInfo:nil 
         repeats:YES]; 
    } 

    NSInteger hours = -remainingSec/3600; 
    NSInteger remainder = ((NSInteger)remainingSec)% 3600; 
    NSInteger minutes = -remainder/60; 
    NSInteger seconds = -remainder % 60; 

    //NSString * stringvalue=[[NSString alloc]initWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds]; 
    int hoursvalue=hour+hours; 
    int minutsvalue=minute+minutes; 
    stopWatchLabel.text=[NSString stringWithFormat:@"%i:%i",hoursvalue,minutsvalue]; 
}