对象泄漏:添加UIImageView并将其移除到UIScrollView
问题描述:
我想动态添加图像到ScrollView。在添加之前,我会检查ScrollView中是否有子视图,并在for循环中删除它们。对象泄漏:添加UIImageView并将其移除到UIScrollView
当我释放imageview时,我得到一个运行时错误,说明我试图访问一个释放的实例。如果删除了发布声明的应用程序将正常运行,但“建立与分析”显示了泄漏,因为日ImageView的不下降的引用计数..
if ([scrollView.subviews count]>0){
for (int i=0; i<[scrollView.subviews count]; ++i) {
[[scrollView.subviews objectAtIndex:i] removeFromSuperview];
}
}
//Making a scroller with results
int scrollWidth = 0.0f;
int scrollHeight = 0.0f;
for (int i = 0; i<previewImages.count;++i)
{
UIImage *image=[previewImages objectAtIndex:i];
scrollWidth = scrollWidth + image.size.width; // Width of all the images
if (image.size.height > scrollHeight)scrollHeight= image.size.height; // Maximum image height
[image release];
}
float xC = 0.0f;
for (int i=0; i<previewImages.count; ++i) {
UIImage *image=[previewImages objectAtIndex:i];
UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(xC, 0.0f, image.size.width, image.size.height)];
UILabel *subScript = [[UILabel alloc] initWithFrame:CGRectMake(xC, image.size.height-30.0f, image.size.width,30.0f)];
subScript.textColor = [UIColor whiteColor];
subScript.backgroundColor = [UIColor colorWithWhite:0.5f alpha:0.5f];
subScript.text = [imagePaths objectAtIndex:i];
imageview.image = image;
xC = xC + image.size.width;
[image release];
[scrollView addSubview:imageview];
[imageview release];
[scrollView addSubview:subScript];
[subScript release];
}
[scrollView setContentSize:CGSizeMake(scrollWidth , scrollHeight)];
对内存泄漏或通用的最佳实践添加任何建议并从数组中删除视图到scrollView非常感谢!
答
if ([scrollView.subviews count]>0){
for (int i=0; i<[scrollView.subviews count]; ++i) {
[[scrollView.subviews objectAtIndex:i] removeFromSuperview];
}
}
是错误的,因为您要从子视图数组中删除子视图。逆向迭代可以解决这个问题,但我建议将视图保持在分隔数组中。
Hi Tia,感谢您的快速回复。我明白你在说什么反向迭代来清空数组,但你能否详细说明你的第二条评论?另外,它没有解决内存泄漏。 – Wicketman 2010-11-06 21:47:25
我的意思是在初始化视图后将视图保留在私有NSArray中,因此您拥有该数组,那么它更容易管理。关于泄漏,我没有看到你的代码片段有什么问题。你确定有泄漏吗?你是如何测试它的? – tia 2010-11-06 22:07:17
我使用NSZombiesEnabled,它显示我在调试控制台中:*** - [UIImage release]:发送到释放实例的消息。 – Wicketman 2010-11-07 15:51:24