UIScrollView延迟加载图像以减少内存使用并避免崩溃 [英] UIScrollView lazy loading of images to reduce memory usage and avoid crash

查看:80
本文介绍了UIScrollView延迟加载图像以减少内存使用并避免崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用,使用滚动视图加载NSOperation(最大约100sh)的多个图像。我试图在我的ipod 2Gen上测试它并且由于设备上的内存不足而崩溃,但在ipod第4代上工作正常。在第2代,它在加载大约15-20张图像时崩溃。我该如何处理这个问题?

My app, using scrollview that loads multiple images with NSOperation (Max around 100sh). I tried to test it out on my ipod 2Gen and it crashes due to low memory on device, but works fine on ipod 4th Gen. On 2nd Gen, it crashes when it loads about 15-20 images. How should I handle this problem ?

推荐答案

您可以加载图片懒洋洋地。这意味着,例如,滚动视图中一次只有几个图像,这样您就可以设置下一个和前一个图像的动画;当你向右移动时,例如,你还要再加载一个图像;同时,你卸载不再可以直接访问的图像(例如那些留在左边的图像)。

You could load you images lazily. That means, e.g., just a couple of images at a time in your scroll view, so that you can animate to the next and the previous one; when you move to the right, e.g., you also load one more image; at the same time, you unload images that are not directly accessible anymore (e.g. those that have remained to the left).

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

You should make the number of preloaded image sufficiently high so that the user can scroll without waiting at any time; this also depends on how big those images are and where they come from (i.e., how long it takes to load them)... a good starting point would be, IMO, 5 images loaded at any time.

在这里您可以找到一步一步的精彩教程

编辑:

由于上面的链接似乎被打破了,这里是该帖子的最终代码:

Since the link above seems to be broken, here is the final code from that post:

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

这篇关于UIScrollView延迟加载图像以减少内存使用并避免崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆