UIScrollView延迟加载图像以减less内存使用并避免崩溃

我的应用程序,使用滚动视图加载多个图像与NSOperation(Max大约100sh)。 我试图在我的ipod 2Gen上进行testing,并且由于设备上的内存不足而出现故障,但在第二代iPod上运行正常。在第二代时,它在加载大约15-20张图像时崩溃。 我应该如何处理这个问题?

你可以懒洋洋地加载你的图片。 这意味着,例如,在您的滚动视图中一次只有几个图像,以便您可以animation到下一个和上一个; 当你向右移动时,例如,你也加载一个图像; 同时,您卸载不能直接访问的图像(例如,保留在左侧的图像)。

您应该使预加载的图像数量足够高,以便用户可以随时滚动而无需等待; 这也取决于这些图像有多大以及它们来自何处(即,装载它们需要多长时间)…一个好的起点是,IMO随时可以载入5张图像。

在这里你会find一个很好的一步一步的教程 。

编辑:

由于上面的链接似乎被打破,这是来自该职位的最终代码:

-(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]; } } }