我希望NSMuttableArray中的每个对象都显示4秒。然后以这种方式迭代数组中的所有项目。相反,我得到的结果是所有项目都出现,并且在这段时间后消失在一起。
-(void)showTreasures{
for (int i = 0; i < _treasures.count; i++)
{
SKSpriteNode *obj = [_treasures objectAtIndex:i];
SKAction *show = [SKAction runBlock:^{
obj.hidden = NO;
}];
SKAction *wait = [SKAction waitForDuration:4];
SKAction *hide = [SKAction runBlock:^{
obj.hidden = YES;
}];
SKAction *sequence = [SKAction sequence:@[show, wait, hide]];
[obj runAction:sequence completion:^{
NSLog(@"Item %d", i);
}];
}
}
答案 0 :(得分:3)
我认为递归方法,调用自身的方法很好。 您可以创建所有对象的数组(SKSpriteNode)并将其传递给获取第一个(或最后一个)对象并运行适当操作的方法,删除该对象并再次调用该方法:
NSMutableArray *arrOfObject = //arrat with all of the sprites you want to show
[self runShowAction:arrOfObject];
-(void)runShowAction:(NSMutableArray*)array {
//if no object in the array return
if(array.count <= 0) return;
SKSpriteNode *obj = [array firstObject];
//Run your code here
//...
//On completion remove object from array and run this method again
[obj runAction:sequence completion:^{
NSLog(@"Item %d", i);
[array removeObject:obj];
[self runShowAction:array];
}];
}
答案 1 :(得分:0)
为什么不使用数组来建立所有操作的列表,然后运行所有这些操作的序列?
-(void)showTreasures
{
NSMutableArray *actions = [NSMutableArray array];
for (int i = 0; i < _treasures.count; i++)
{
SKSpriteNode *obj = [_treasures objectAtIndex:i];
SKAction *show = [SKAction runBlock:^{
obj.hidden = NO;
}];
SKAction *wait = [SKAction waitForDuration:4];
SKAction *hide = [SKAction runBlock:^{
obj.hidden = YES;
}];
SKAction *finish = [SKAction runBlock:^{
NSLog(@"Item %d", i);
}];
[actions addObjectsFromArray:@[show, wait, hide, finish]];
}
SKAction *sequence = [SKAction sequence:actions];
[obj runAction:sequence completion:^{
NSLog(@"Finished all items");
}];
}