Re: Accurate time delay without locking up CPU
Re: Accurate time delay without locking up CPU
- Subject: Re: Accurate time delay without locking up CPU
- From: Shawn Erickson <email@hidden>
- Date: Thu, 17 Oct 2002 19:05:02 -0700
On Thursday, October 17, 2002, at 05:18 PM, Justin Lundy wrote:
I'm writing a turn based game (a card game) where the user plays
against the computer. The problem I'm running into is that I want to
add delays in between certain graphical actions, such as making a
NSTextField flash:
- (void)addPointsToPlrScore:(int)points
{
int flashes = 3;
for (flashes = 3; flashes >= 0; flashes--) {
[plrScoreAdd setStringValue:[NSString
stringWithFormat:@"+%d",points]];
// pause for 0.25 seconds?
[plrScoreAdd setStringValue:[NSString stringWithFormat:@""]];
// pause for 0.25 seconds?
}
}
Look at the docs for NSThread or use an NSTimer to trigger the next
step in the above loop.
I think using an NSTimer would be better because using NSThread to
sleep things will block the processing of user events while it sleeps
unless your addPointToPlrScore is running in a secondary thread.
Are you expecting the above to redraw on the screen while you sleep? as
coded I don't think it will.
Something like the follpwing...
(assuming some things below are ivars, etc. and this is not tested)
- (void)addPointsToPlrScore:(int)points
{
flashes = 6; //flashes 3 times but calls updateScore 6 times to do that
NSNumber *score = [[NSNumber numberWithInt:points] retain];
[self updateScore:score];
timer = [NSTimer scheduledTimerWithTimeInterval:0.25
target:self
selector:@selector(updateScore:)
userInfo:score
repeats:YES];
}
- (void)updateScore:(id)score
{
if (flashes % 2) {
[plrScoreAdd setStringValue:[NSString stringWithFormat:@""]];
} else {
[plrScoreAdd setStringValue:[NSString stringWithFormat:@"+%d",
[score intValue]]];
}
if (--flashes == 0) {
[timer invalidate];
[score release];
}
}
-Shawn
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.