我在UIKit中遇到了UIKit中的一个bug。将它们添加到UIViews数组中会导致内存泄漏。我制作了一个简单的演示项目,它创建了10个视图的动画,这些视图随着重力的应用而下降,并与包围视图的界限发生冲突。(代码如下)仪器中的泄漏模板为每次运行报告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字节的内存块之外的所有内存块,但是当冲突完成时,冲突就不再起作用了。有人能提出一个可行的解决办法吗?
发布于 2014-05-05 03:01:25
我遇到了同样的问题,但是通过使用UICollisionBehavior的设置边界来修复内存泄漏
addBoundaryWithIdentifier不幸的是,使用translatesReferenceBoundsIntoBoundary和setTranslatesReferenceBoundsIntoBoundaryWithInsets设置边界给我造成了泄漏。
https://stackoverflow.com/questions/21486600
复制相似问题