在我的应用程序中,我有一些图像从UIView内部落下。 UIImageView对象是动态创建的,可以向下移动。我的问题是,物体在移出屏幕区域后是否会自行毁坏?或者我应该手动完成以提高性能?
答案 0 :(得分:2)
一旦对某个对象没有更强的引用,它就会被释放。您可能需要清楚的两个引用将是变量指针,以及superview对它的引用。因此,您需要执行以下操作:
[imageView removeFromSuperView];
imageView = nil;
可能还有更多,因为你没有提供任何代码(例如,如果你有一个指向数组中对象的指针,你也需要删除它。)
答案 1 :(得分:1)
如果您没有任何其他指向图像视图的指针(在ARC中),则从超级视图中删除即可。最高效的模式是保留指向屏幕外图像视图的指针池。在伪代码中:
// this assumes the number onscreen is relatively small, in the tens or low hundreds
// this works better when the number on screen is relatively constant (low variance)
// say the animation looks something like this:
- (void)makeAnImageFall:(UIImage *)image {
CGRect startFrame = // probably some rect above the superview's bounds
UIImageView *imageView = [self addImageViewWithImage:image frame:frame]; // see below
[UIView animateWithDuration:1.0 animations:^{
imageView.frame = // probably some rect below the superview's bounds
} completion:^(BOOL finished) {
[self removeImageView:imageView]; // see below
}];
}
然后这些方法可以处理池:
- (UIImageView *)addImageViewWithImage:(UIImage *)image frame:(CGRect)frame {
UIImageView *imageView;
// assume you've declared and initialized imageViewPool as an NSMutableArray
// or do that here:
if (!self.imageViewPool) self.imageViewPool = [NSMutableArray array];
if (self.imageViewPool.count) {
imageView = [self.imageViewPool lastObject];
[self.imageViewPool removeLastObject];
} else {
imageView = [[UIImageView alloc] init];
}
imageView.image = image;
imageView.frame = frame;
[self.view addSubview:imageView];
return imageView;
}
- (void)removeImageView:(UIImageView *)imageView {
imageView.image = nil;
[self.imageViewPool addObject:imageView];
[imageView removeFromSuperview];
}
好主意是我们避免了许多图像视图的创建 - 破坏相对昂贵的流失。相反,我们在他们第一次需要时(懒洋洋地)创造它们。一旦我们达到图像视图的高水位线,我们就不会再分配另一个。