I'm trying t开发者_JS百科o play animations in sequence but I'm having issues playing them as a for loop iterates through the list of objects in an array.
it will move through the array but it won't play each one it just plays the last.
-(void) startGame {
gramma.animationDuration = 0.5;
// Repeat forever
gramma.animationRepeatCount = 1;
int r = arc4random() % 4;
[colorChoices addObject:[NSNumber numberWithInt:r]];
int anInt = [[colorChoices objectAtIndex:0] integerValue];
NSLog(@"%d", anInt);
for (int i = 0; i < colorChoices.count; i++) {
[self StrikeFrog:[[colorChoices objectAtIndex:i] integerValue]];
//NSLog(@"%d", [[colorChoices objectAtIndex:i] integerValue]);
sleep(1);
}
}
it moves through the whole cycle really fast and sleep isn't doing anything to allow it to play each animation... any suggestions?
Use an NSTimer so the run loop has time to process. Drawing does not begin until after startGame returns.
Edit:
-(void) myTimerMethod:(NSTimer *)inTimer {
if ( mPosition < [colorChoices count] ) {
[self StrikeFrog:[[colorChoices objectAtIndex:mPosition] integerValue]];
mPosition += 1;
} else {
[inTimer invalidate];
}
}
To start it:
mPosition = 0;
[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(myTimerMethod:) userInfo:nil repeats:YES];
If you need to be able to stop the timer midway through, retain a reference to it so you can invalidate it as needed.
I suspect I know what is wrong, but don't know the "right" fix it, depending on how "right" you want to be. What's happening is simple - Objective C doesn't call functions, it passes messages. When you do [self StrikeFrog] a message gets placed on a queue to be performed as soon as the queue can be drained; you are probably receiving all the messages at the end because StrikeFrog is not getting called before sleep- it's getting called whenever the queue thread becomes unblocked. In a single threaded application, for example, the net effect would be to sleep for (colorChoices.count) seconds and then execute all of the StrikeFrog events after you exit out of the for loop, since that's the first time the event queue can send your events. In other words, all "function calls" in Obj C are asynchronous, no matter how many threads are being used.
I would suggest either going lower-level with C or higher-level with CoreAnimation. If neither one of these suits you, you can try NSObject performSelector:withObject:afterDelay: to queue up a whole bunch of events that each get executed after some delay. This method has a lot of issues you'd have to work out, though, so be careful.
精彩评论