【发布时间】:2011-10-10 19:48:59
【问题描述】:
我的应用程序,使用滚动视图,通过 NSOperation 加载多个图像(最大约 100sh)。我试图在我的 ipod 2Gen 上对其进行测试,但由于设备内存不足而崩溃,但在 ipod 4th Gen 上运行良好。在第 2 代,它在加载大约 15-20 个图像时崩溃。我应该如何处理这个问题?
【问题讨论】:
标签: objective-c ios memory-management uiscrollview
我的应用程序,使用滚动视图,通过 NSOperation 加载多个图像(最大约 100sh)。我试图在我的 ipod 2Gen 上对其进行测试,但由于设备内存不足而崩溃,但在 ipod 4th Gen 上运行良好。在第 2 代,它在加载大约 15-20 个图像时崩溃。我应该如何处理这个问题?
【问题讨论】:
标签: objective-c ios memory-management uiscrollview
你可以懒惰地加载你的图片。这意味着,例如,在您的滚动视图中一次只有几张图像,以便您可以动画到下一张和上一张;当您向右移动时,例如,您还加载了一张图片;同时,您会卸载不再可直接访问的图像(例如留在左侧的图像)。
您应该使预加载图像的数量足够多,以便用户可以随时滚动而无需等待;这还取决于这些图像有多大以及它们来自哪里(即加载它们需要多长时间)......一个好的起点是,IMO,随时加载 5 张图像。
在这里您可以找到nice step by step tutorial。
编辑:
由于上面的链接似乎已损坏,以下是该帖子的最终代码:
-(void)scrollViewDidScroll:(UIScrollView *)myScrollView {
/**
* calculate the current page that is shown
* you can also use myScrollview.frame.size.height if your image is the exact size of your scrollview
*/
int currentPage = (myScrollView.contentOffset.y / currentImageSize.height);
// display the image and maybe +/-1 for a smoother scrolling
// but be sure to check if the image already exists, you can do this very easily using tags
if ( [myScrollView viewWithTag:(currentPage +1)] ) {
return;
}
else {
// view is missing, create it and set its tag to currentPage+1
}
/**
* using your paging numbers as tag, you can also clean the UIScrollView
* from no longer needed views to get your memory back
* remove all image views except -1 and +1 of the currently drawn page
*/
for ( int i = 0; i < currentPages; i++ ) {
if ( (i < (currentPage-1) || i > (currentPage+1)) && [myScrollView viewWithTag:(i+1)] ) {
[[myScrollView viewWithTag:(i+1)] removeFromSuperview];
}
}
}
【讨论】: