iPhone sdk: Countdown timer
Please help. I want to create countdown timer using iphone sdk. I have current time:
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm"];
NSString *currentTime = [dateFormatter stringFromDate:today];
[dateFormatter release];
and time(s) from database. Eg.: currentTime is 19:18:30, time from database is 19:2开发者_开发百科0:01. So the timer should be set to 0:01:31 and begin the countdown. When reach the 0:00:00, take another time from database (eg: 19:21:00), set up timer (0:00:59) and star countdown again. When reach the 0:00:00, take... The timer should be displayed by UILabel.
Please help. It begins to make me mad. :)
try this. I've just written only required methods for the solution. Don't forget to implement dealloc etc.
CountdownViewController.h
@interface CountdownViewController : UIViewController {
IBOutlet UILabel *clockLabel;
NSDate *databaseDate;
NSTimer *timer;
}
@property(nonatomic, retain) IBOutlet UILabel *clockLabel;
@property(nonatomic, retain) NSDate *databaseDate;
@end
CountdownViewController.m
@implementation CountdownViewController
@synthesize clockLabel;
@synthesize databaseDate;
- (void) showClock {
NSTimeInterval remainingSec = [databaseDate timeIntervalSinceNow];
if (!timer || remainingSec <= 0) {
[timer invalidate];
timer = nil;
// getting time from database
self.databaseDate = [NSDate dateWithTimeIntervalSinceNow:20.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;
clockLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}
@end
精彩评论