我认为将一组动画传递给一个一个接一个地运行所有动画的内部函数是个好主意,因此我不需要在彼此之间嵌套动画以及彼此的完成块。所以我写了一个小方法来测试它,并猜测是什么,它像地狱一样崩溃。但我不明白为什么。这是我的方法:
+(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;
}];
当我调试它时,它会仔细检查我的所有动画,用完成块调用最终动画然后崩溃致命。我在这里做错了什么?
答案 0 :(得分: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);