我认为将一组动画传递到一个内部函数,该函数依次运行所有动画将是一个绝妙的主意,因此我不需要将动画嵌套在彼此以及彼此的完成 block 中。所以我写了一个小方法来测试这个,你猜怎么着,它崩溃得很厉害。但我不明白为什么。这是我的方法:
+(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;
}];
当我调试它时,它会友好地遍历我的所有动画,使用其完成 block 调用最终动画,然后致命地崩溃。我在这里做错了什么?
最佳答案
问题是,调用 NSMutableArray
的 -addObject:
将保留但不会复制添加的对象。当您声明一个 block 时,它位于堆栈中,该堆栈将在作用域末尾被销毁。要使其进入堆,您必须Block_copy
或向该 block 发送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);
关于iphone - 传递动画数组时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9602221/