Objective c - NSTimer, CADisplayLink, Thread

2019-08-29 23:21发布

I'm currently making a little game with a countdown timer. I use an NSTimer, you can get extra time or less time, depends on your action. When I'm adding or removing seconds to my timer I have an issue with the time label. The issue is due to me, I'm calling my method timerAction, who set the new time in the label when I'm adding or removing time and then the NSTimer is calling the method too. If I don't call timerAction, I must wait 1 second to refresh the label with NSTimer.

So, what should I do to solve my issue ?

Thanks for your help.

1条回答
地球回转人心会变
2楼-- · 2019-08-29 23:51

Firstly, I would like to ask about your code.

Besides, in this case, I will do like this pattern.

@property (nonatomic) NSInteger remainingTime;
@property (nonatomic) NSTimer *timer;

timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerAction) userInfo:nil repeats:YES]; 

- (void)timerAction {
    if (!countingFinish) {
       remainingTime --;
       //backend regular action
       [self frontEndUpdate];
    }else {
       [timer invalidate];
    }
}

- (bool)countingFinish {
    return (reamainingTime <= 0);
}

- (void)frontEndUpdate {
    //update time label, or other front end update action
}

- (void)addCountingRemaining:(NSInteger) _sec {
     remainingTime += _sec;
     [self frontEndUpdate];
}

btw, this is juz draft code. hope it helps

查看更多
登录 后发表回答