我有一个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 2015-05-19 14:41:05.827餐厅4206:77915 2015-05-19 14:41:08.828餐厅4206:77915
发布于 2015-05-19 21:19:20
为什么不在计时器之前调用您的方法呢?
[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];发布于 2015-05-19 23:37:46
有些评论确实很有帮助,特别是添加了罗曼底谷建议的日志。事实证明,[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];离开这里以防对任何人有帮助。
https://stackoverflow.com/questions/30336298
复制相似问题