实时倒计时最有效的方式

时间:2012-01-12 13:10:11

标签: objective-c ios nstimer

我正在编写一个包含倒计时的应用程序。倒计时显示在标签上,但我不确定我是否最有效地更新标签。我正在使用间隔为1秒的计时器。有没有什么方法可以消耗更少的资源?此外,这会在旧设备上崩溃吗?

- (void)viewDidLoad
{
    [super viewDidLoad];
//Create Calendar for NSDates
gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]];

//Create NSDate lunchTime based on Now
now = [NSDate date];
NSDateComponents *compsOfNow = [gregorian components:(NSWeekdayCalendarUnit |NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit |NSYearCalendarUnit|NSMonthCalendarUnit|NSEraCalendarUnit)fromDate:now];
[compsOfNow setHour:12];
[compsOfNow setMinute:50];
lunchTime = [gregorian dateFromComponents:compsOfNow];

//Create timer and set text
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerTicked:) userInfo:nil repeats:YES];
lunchCountdownLabel.text = [NSString stringWithFormat:@"%i:%i:%i", difference.hour, difference.minute, difference.second];

}

- (void)timerTicked:(NSTimer*)timer {
now = [NSDate date];
difference = [gregorian components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:now toDate:lunchTime options:0];
lunchCountdownLabel.text = [NSString stringWithFormat:@"%i:%i:%i", difference.hour, difference.minute, difference.second];
NSLog(@"Timer Ticked");

感谢您的意见,

谢谢,

HBhargava

1 个答案:

答案 0 :(得分:0)

这对我来说似乎很好......只要记住一旦你完成它就会使计时器失效。(你现在还没有这样做。)