問題描述
我的應用程序,使用滾動視圖,通過 NSOperation 加載多個圖像(最大約 100sh).我試圖在我的 ipod 2Gen 上對其進行測試,但由于設備內存不足而崩潰,但在 ipod 4th Gen 上運行良好.在第 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 延遲加載圖片以減少內存使用并避免崩潰的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!