2011-04-15 65 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]; 
}