我的日期倒计时不会更新

时间:2014-07-04 14:46:29

标签: ios objective-c nsdate

我想得到今天的时间,加上10分钟,并在标签上显示10分钟倒计时到保存的时间。

-(void)updateCountdown {

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"mm:ss"]; //Format minutes and seconds

NSDate *startingDate = [NSDate date]; //Get todays date/time right now
NSDate *endingDate = [[NSDate date] dateByAddingTimeInterval:600]; //Add 600 seconds     / 10 mins to it

NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSMinuteCalendarUnit|NSSecondCalendarUnit;


//I thought this would keep updating until the startingDate reached the same time as endingDate????
NSDateComponents *dateComponants = [calendar components:unitFlags fromDate:startingDate toDate:endingDate options:0];

//Get the minutes and seconds
NSInteger minutes = [dateComponants minute];
NSInteger seconds = [dateComponants second];

//Put mins and seconds into a string
NSString *countdownText = [NSString stringWithFormat:@"%d Minute %d Seconds", minutes, seconds];
timeLabel.text = countdownText; //Set my label as the string
[self performSelector:@selector(updateCountdown) withObject:nil afterDelay:1]; //Keep updating }

标签显示“10分00秒”,但不倒计时。

我想要的是从开始日期到结束日期倒计时: e.g

startingDate = 12:00 endingDate = 12:10

标签将显示从10分钟开始的差异,直到startingDate为12:10

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

每次调用此方法时都会设置endingDatestartingDate,这意味着每次都会重新创建它。您需要使它成为类的实例变量,以便在方法的不同执行中保留它。例如:

@property (strong) NSDate *endingDate;
@property (strong) NSDatd *startingDate;

然后你的方法将是:

-(id)init {

*startingDate = [NSDate date]; //Get todays date/time right now
*endingDate = [[NSDate date] dateByAddingTimeInterval:600]; //Add 600 seconds     / 10 mins to it

...

}

-(void)updateCountdown {

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"mm:ss"]; //Format minutes and seconds

NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSMinuteCalendarUnit|NSSecondCalendarUnit;


//I thought this would keep updating until the startingDate reached the same time as endingDate????
NSDateComponents *dateComponants = [calendar components:unitFlags fromDate:startingDate toDate:endingDate options:0];

//Get the minutes and seconds
NSInteger minutes = [dateComponants minute];
NSInteger seconds = [dateComponants second];

//Put mins and seconds into a string
NSString *countdownText = [NSString stringWithFormat:@"%d Minute %d Seconds", minutes, seconds];
timeLabel.text = countdownText; //Set my label as the string
[self performSelector:@selector(updateCountdown) withObject:nil afterDelay:1]; //Keep updating }

应该这样做。