Monkeyanator
Monkeyanator

Reputation: 1416

Displaying Each Element of an Array One by One

I have an array of SKSpriteNodes (although, for the purposes of this question, they may as well be UIViews [concept should be the same either way]). I am attempting to add the first element to the view, begin a 3 second delay, add the second element to the view, begin a 3 second delay, etc.. My initial thought would be a recursive function using NSTimer, but I'm not sure that would be the best way to go. Any tips?

Upvotes: 1

Views: 63

Answers (1)

godel9
godel9

Reputation: 7390

Option 1

Use SKAction with performSelector:

self.nextIndex = 0;
SKAction *action = [SKAction sequence:@[[SKAction waitForDuration:3.0],
                                        [SKAction performSelector:@(addNextItem) onTarget:self]]];
[self runAction:action];

Then, define addNextItem:

- (void)addNextItem
{
    [self addChild:myArray[self.nextIndex++]];
    if(self.nextIndex < [myArray count]) {
        SKAction *action = [SKAction sequence:@[[SKAction waitForDuration:self.nextWait],
                                                [SKAction performSelector:@(addNextItem) onTarget:self]]];
        [self runAction:action];
    }
}

Option 2

If you're familiar with blocks, you can use blocks for this type of thing as well:

__block NSUInteger index = 0;
void (^addItem)(void) = ^(void) {
    SKNode *node = myArray[index++];
    [self addChild:node];
};
SKAction *action = [SKAction sequence:@[[SKAction waitForDuration:3.0],
                                        [SKAction runBlock:addItem],
                                        [SKAction waitForDuration:3.0],
                                        [SKAction runBlock:addItem],
                                        [SKAction waitForDuration:3.0],
                                        [SKAction runBlock:addItem],
                                        [SKAction waitForDuration:3.0],
                                        [SKAction runBlock:addItem]]];
[self runAction:action];

Here are some references for using blocks:

Upvotes: 2

Related Questions