我遇到了我认为是UICollisionBehavior
in的错误UIKit
。将它们添加到数组UIViews
会导致内存泄漏。我整理了一个简单的演示项目,该项目创建了 10 个动画,其中一组视图在重力作用下下落,并与封闭视图的边界发生碰撞。(代码如下。) 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;
}
}
我真的很希望能够在我正在开发的应用程序中实现碰撞,但是这种泄漏使它无法使用。我已经尝试将碰撞行为保存在属性中并重用它。这可以防止泄漏除了一个 64 字节的内存块之外的所有内存,但是当它完成时冲突不再起作用。任何人都可以提出一个可行的解决方法吗?