2012-03-07 30 views
0

我认为将动画数组传递给一个内部函数会一个接一个地运行所有动画是一个绝妙的想法,所以我不需要在彼此之间嵌套动画,彼此的完成块。所以我写了一个小方法来测试这个,猜猜它是什么,它会像地狱一样崩溃。但我不明白为什么。这是我的方法:当传递动画数组时,应用程序崩溃

+(void) internalAnimateWithArrayOfAnimationBlocks:(NSArray*) animationBlocks withIndex:(NSUInteger) index withCompletionAnimation:(void (^)(BOOL finished)) completionBlock { 
    __block NSArray* newAnims = animationBlocks; 
    __block NSUInteger theIndex = index; 
    if (index < [newAnims count] - 1) { 
    [UIView animateWithDuration:0.1 animations:^{ 
     void (^animBlock) (void) = [newAnims objectAtIndex:theIndex]; 
     animBlock(); 
     theIndex++; 
     [RMAnimater internalAnimateWithArrayOfAnimationBlocks:newAnims withIndex:theIndex withCompletionAnimation:completionBlock]; 
    }]; 
    } 
    else { 
    [UIView animateWithDuration:0.1 animations:^{ 
     void (^animBlock) (void) = [newAnims objectAtIndex:theIndex]; 
     animBlock(); 
     theIndex++; 
    } completion:completionBlock]; 
    } 
} 

+(void) animateWithArrayOfAnimationBlocks:(NSArray*) animationBlocks withCompletionAnimation:(void (^)(BOOL finished)) completionBlock { 
    [RMAnimater internalAnimateWithArrayOfAnimationBlocks:animationBlocks withIndex:0 withCompletionAnimation:completionBlock]; 
} 

我通过这个动画是这样的:

NSMutableArray* animations = [NSMutableArray array]; 
[animations addObject:^{ 
    CGRect frame = theTile.textField.frame; 
    frame.origin.x -= 10; 
    theTile.textField.frame = frame; 
}]; 

当我调试它,它亲切地通过我的所有动画去,用其完成块调用最终的动画,然后崩溃致命。我在这里做错了什么?

+1

“崩溃致命”不是很具体。怎么了? – Jim 2012-03-07 13:21:09

回答

1

问题是,调用-addObject:NSMutableArray将保留但不复制添加的对象。当你声明一个块时,它会在堆栈中,这将在范围的末尾被销毁。要成堆,您必须Block_copy或发送copy消息到块。所以要解决您的问题,您必须:

NSMutableArray* animations = [NSMutableArray array]; 
void (^animBlock)(void) = Block_copy(^{ 
    CGRect frame = theTile.textField.frame; 
    frame.origin.x -= 10; 
    theTile.textField.frame = frame; 
}); 
[animations addObject:animBlock]; 
Block_release(animBlock); 
+0

我以为是这样的..非常感谢! – Fuggly 2012-03-07 14:00:23