UICollisionBehavior内存泄漏

时间:2014-01-31 17:42:33

标签: ios objective-c uikit-dynamics

我在UICollisionBehavior中遇到了我认为是UIKit的错误。将它们添加到UIViews数组会导致内存泄漏。我整理了一个简单的演示项目,该项目创建了一组视图的动画,这些视图随着重力的应用而下降,并与封闭视图的边界发生碰撞。 (下面的代码。)Instruments中的Leaks模板报告每次运行有9个64字节的泄漏。

- (void)doAnimation
{
    self.animateButton.enabled = NO;

    CGFloat left = 12.0f;
    NSMutableArray *items = [NSMutableArray new];

    // set up an array of views and add them to the superview
    while (left < self.view.bounds.size.width - 12.0f) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(left, 70, 32, 32)];
        left += 34.0f;
        [self.view addSubview:view];
        view.backgroundColor = [UIColor grayColor];
        [items addObject:view];
    }

    // create a gravityBehavior and initialize with views array
    UIGravityBehavior *gravity = [[UIGravityBehavior alloc] initWithItems:items];
    [self.animator addBehavior:gravity];

    // create a collisionBehavior and initialize with views array
    UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:items];
    collision.translatesReferenceBoundsIntoBoundary = YES;
    [self.animator addBehavior:collision];
}

// UIDynamicAnimatorDelegate method that's called when collision animation is complete
- (void)dynamicAnimatorDidPause:(UIDynamicAnimator *)animator
{
    // get a collision behavior in order to access its items for loop below
    UICollisionBehavior *behavior;
    for (UIDynamicBehavior *oneBehavior in animator.behaviors) {
        if ([oneBehavior isKindOfClass:[UICollisionBehavior class]]) {
            behavior = (UICollisionBehavior *)oneBehavior;
            break;
        }
    }

    // reset the UIDynamicAnimator property's behaviors for next run
    [self.animator removeAllBehaviors];

    self.dropCount++;

    // remove all subviews
    for (UIView *view in behavior.items) {
         [view removeFromSuperview];
    }

    // run the animation again or break
    if (self.dropCount < 10) {
        [self doAnimation];
    } else {
        self.animateButton.enabled = YES;
    }
}

我真的希望能够在我正在处理的应用程序中实现冲突,但这种泄漏使其无法使用。我试过在属性中保存collisionBehavior并重用它。这可以防止泄漏除了一个64字节的内存之外的所有内存,但是当完成时,冲突不再起作用。任何人都可以建议一个有效的解决方法吗?

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题但通过使用UICollisionBehavior的

设置边界来修复内存泄漏
addBoundaryWithIdentifier

不幸的是,设置translatesReferenceBoundsIntoBoundarysetTranslatesReferenceBoundsIntoBoundaryWithInsets的边界会导致我的泄密。