我正在尝试加载滚动视图50 png图像,我选择通过延迟加载来执行此操作。但是我仍然有很大的内存问题,当我滚动30页时我的应用程序崩溃了。
请帮助我理解为什么会这样,我的代码是:
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];
}
答案 0 :(得分:0)
将其添加到pageViews数组后,应该发布newPageView。
答案 1 :(得分:0)
我发现了问题,它正在创建newPageView。所以我将其更改为以下内容,我的应用程序现在不会崩溃。
UIImageView *newPageView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:string ofType:@"png"]]];
感谢您的帮助。