iphone - 传递动画数组时应用程序崩溃

标签 iphone ios ipad uiview uiviewanimation

我认为将一组动画传递到一个内部函数,该函数依次运行所有动画将是一个绝妙的主意,因此我不需要将动画嵌套在彼此以及彼此的完成 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/

相关文章:

ios - iPad:横向呈现 UIImagePickerController 会在关闭时旋转我的其他 View Controller

iphone - ios 6上的导航栏与其他 View 重叠

iOS 应用程序配置文件错误,配置文件未关联

ios - ios中的字符串处理

iphone - 如何在 ipad 编码中将 splitview 添加到我的基于 View 的应用程序

iphone - Objective C 中 UITableView 标题中的 UILabel

iphone - 更快的iPhone PNG动画

iphone - 配置 UItableView 不在 iPhone 上滚动

ios - 在swift4中查找按钮的文本颜色

ios - 如何为 UICollectionView 单元格选择设置动画