我想加載到scrollview 50 PNG圖像,我選擇通過延遲加載來做到這一點。但是我仍然有很大的內存問題,當我滾動30頁時,我的應用程序崩潰。ScrollView內存問題
請幫助我瞭解爲什麼會出現這種情況,我的代碼是:
UIImage *1 = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"30" ofType:@"png"]];
....
imageArray = [NSArray arrayWithObjects:1,2,3,4, ...];
- (void)loadPage:(NSInteger)page
{
if (page < 0 || page >= imageArray.count)
{
return;
}
UIView *pageView = [pageViews objectAtIndex:page];
if ((NSNull*)pageView == [NSNull null])
{
CGRect frame = self.scrollView.bounds;
frame.origin.x = frame.size.width * page;
frame.origin.y = 0.0f;
UIImageView *newPageView = [[UIImageView alloc] initWithImage:[imageArray objectAtIndex:page]];
newPageView.contentMode = UIViewContentModeScaleAspectFit;
newPageView.frame = frame;
[self.scrollView addSubview:newPageView];
[pageViews replaceObjectAtIndex:page withObject:newPageView];
}
}
- (void)purgePage:(NSInteger)page
{
if (page < 0 || page >= imageArray.count)
{
return;
}
UIView *pageView = [pageViews objectAtIndex:page];
if ((NSNull*)pageView != [NSNull null])
{
[pageView removeFromSuperview];
[pageViews replaceObjectAtIndex:page withObject:[NSNull null]];
}
}
- (void)loadVisiblePages
{
CGFloat pageWidth = self.scrollView.frame.size.width;
NSInteger page = (NSInteger)floor((self.scrollView.contentOffset.x * 2.0f + pageWidth)/(pageWidth * 2.0f));
self.pageControl.currentPage = page;
// Work out which pages you want to load
NSInteger firstPage = page - 1;
NSInteger lastPage = page + 1;
// Purge anything before the first page
for (NSInteger i=0; i<firstPage; i++)
{
[self purgePage:i];
}
for (NSInteger i=firstPage; i<=lastPage; i++)
{
[self loadPage:i];
}
for (NSInteger i=lastPage+1; i<imageArray.count; i++)
{
[self purgePage:i];
}
NSString *string = [NSString stringWithFormat:@"%i.png",page+1];
layer = [UIImage imageNamed:string];
}
in puragePage :, set pageView = nil將其替換爲NSNull實例後。看看這是否給你一個更好的性能結果。 – jmstone617 2012-04-03 22:52:34