1
我想動態添加圖像到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非常感謝!
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