我有一个工作正常的NSTimer,并以1秒的间隔倒计时。但我希望计时器在没有1秒延迟的情况下立即触发。
我认为调用[timer fire]
应该适用于此(描述为here),但它并没有什么不同。我希望定时器的触发速度与我将间隔调度为0的速度一样快。
- (void)onStartButtonPressed:(UIButton*)sender
{
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:tv];
NSIndexPath* indexPath = [tv indexPathForRowAtPoint:buttonPosition];
NSInteger index = indexPath.row;
// starts timer for cell at the index path
if (indexPath != nil)
{
NSTimer* timer = [timerArray objectAtIndex: index];
if ([timer isEqual:[NSNull null]]) {
NSLog(@"It's empty");
// start timer
NSTimer timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(onTick:)
userInfo:indexPath
repeats:YES];
// [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
NSLog(@"before timer fire");
[timer fire];
// update data array of timer objects and countdowns
NSInteger selectedTimeIdx = [[selectedTimeIdxArray objectAtIndex: index] integerValue];
NSInteger selectedTime = [pickerTimeArray[selectedTimeIdx] integerValue];
[timerArray replaceObjectAtIndex:index withObject:timer];
[countdownArray replaceObjectAtIndex:index withObject:[NSNumber numberWithInteger:selectedTime*60]];
} else {
NSLog(@"It's not empty");
}
}
- (void)onTick:(NSTimer *)timer
{
NSLog(@"on tick method starts");
// get the timer's owner's index path and update label
NSIndexPath* indexPath = [timer userInfo];
NSInteger index = indexPath.row;
// update countdown
NSInteger countdown = [[countdownArray objectAtIndex: index] integerValue];
[countdownArray replaceObjectAtIndex:index withObject:[NSNumber numberWithInteger:--countdown]];
// NSLog(@"countdown: %ld", (long)countdown);
[tv reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
// NSLog(@"Tic indexPath: %@", indexPath);
if (countdown == 0)
{
[timer invalidate];
timer = nil;
}
}
计时器工作但我不希望最初触发它有1秒的延迟。我想让计时器立即启动。
编辑:我添加了rmaddy建议的日志。以下是我的结果(我将间隔时间更改为3):
2015-05-19 14:41:02.827餐厅[4206:77915]在计时器开火前
2015-05-19 14:41:02.827餐厅[4206:77915] on tick方法开始
2015-05-19 14:41:05.827餐厅[4206:77915] on tick方法开始
2015-05-19 14:41:08.828餐厅[4206:77915] on tick方法开始
答案 0 :(得分:1)
为什么不在计时器之前调用你的方法
[self onTick:nil];
//usual timer code here
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(onTick:)
userInfo:indexPath repeats:YES];
[self onTick:timer];
答案 1 :(得分:0)
有些评论非常有用,特别是按照rmaddy的建议添加日志。事实证明[timer fire]
工作正常。
我自己很困惑,因为显示倒计时的timerLabel
正在我的单元格中更新,延迟时间为1秒,我认为这意味着计时器实例化被延迟了。
一旦我看到问题确实存在,我所要做的就是更新我实例化计时器的同一块中的单元格(而不仅仅是onTick
)。
我刚刚将此添加到我的onStartButtonPressed
,一切正常,因为我想要它。
// update countdown
NSInteger countdown = [[countdownArray objectAtIndex: index] integerValue];
[countdownArray replaceObjectAtIndex:index withObject:[NSNumber numberWithInteger:--countdown]];
// cell label gets updated right at start button press
[tv reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
离开这里以防万一。