no delay achieved with NSTimer

我只是一个虾纸丫 提交于 2020-01-17 15:29:13

问题


I want to delay between each output result for say, 1 second. The code below is not delaying but is processing correctly. Why is it not delaying between each dealCard?

- (IBAction)startPause
{
    if ([self.deal length]>cardNum) {
        timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(dealCard) userInfo:nil repeats:NO];
        [timer fire];
    }
}


- (void) dealCard{
    card.text = [NSString stringWithFormat:@"%i",cardNum+1];
    cardTo.text = [self.deal substringWithRange:(NSRange){(cardNum+self.randCut)%[self.cardList count],1}];
    cardNum=cardNum + 1;
    [self startPause];
}

回答1:


According to the documentation fire "Causes the receiver’s message to be sent to its target." Which is why it's firing instantly.

Your timer is also not scheduled, so it would never fire on it's own.

Create your timer like this instead, which creates a timer, and schedules it in a single statement.

timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                         target:self
                                       selector:@selector(dealCard)
                                       userInfo:nil
                                        repeats:NO];

And remove the [timer fire] line completely, as it will fire itself after it's time interval is up.



来源:https://stackoverflow.com/questions/17055297/no-delay-achieved-with-nstimer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!