在UIScrollView中加载200多个子视图图像时程序崩溃

我正在使用ALAssetLibrary在iPhone中开发像Photos这样的类似程序。 我试图在scrollview中加载图像。 当专辑有少量图片时,一切正常。 但是当我尝试用200多张照片加载相册时,我的程序结束时没有任何错误消息。 有人知道这个节目吗? 这是我加载滚动视图的代码:

- (void)loadScrollView { for (UIView *v in [scrollview subviews]) { [v removeFromSuperview]; } CGRect scrollFrame = [self frameForPagingScrollView]; scrollview = [[UIScrollView alloc] initWithFrame:scrollFrame]; CGRect workingFrame = scrollview.frame; workingFrame.origin.y = 0; photoCount = [info count]; for(NSDictionary *dict in info) { UIImageView *imageview = [[UIImageView alloc] initWithImage:[dict objectForKey:UIImagePickerControllerOriginalImage]]; [imageview setContentMode:UIViewContentModeScaleAspectFit]; imageview.frame = workingFrame; [scrollview addSubview:imageview]; [imageview release]; [scrollview setPagingEnabled:YES]; [scrollview setDelegate:self]; [scrollview setAutoresizesSubviews:YES]; [scrollview setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight]; [scrollview setShowsVerticalScrollIndicator:NO]; [scrollview setShowsHorizontalScrollIndicator:NO]; workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width; } [self setScrollViewContentSize]; [[self view] addSubview:scrollview]; } 

非常感谢提前!

我个人将所有UIImageView对象放在我的UIScrollView ,但只为那些当前可见的对象设置了它们的图像属性(并清除那些不再可见的图像属性)。 如果你有成千上万的图像,甚至可能太浪费了(也许你甚至不想保留UIImageView对象,即使没有设置image属性),但如果你要处理数百个,我发现它是一个很好的简单解决方案,解决UIImage对象消耗的内存的关键问题:

 - (void)viewDidLoad { [super viewDidLoad]; self.scrollView.delegate = self; // all of my other viewDidLoad stuff... } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self loadVisibleImages]; } - (void)scrollViewDidScroll:(UIScrollView *)scrollView { [self loadVisibleImages]; } - (void)loadVisibleImages { CGPoint contentOffset = self.scrollView.contentOffset; CGRect contentFrame = self.scrollView.bounds; contentFrame.origin = contentOffset; for (UIImageView *imageView in _imageViews) // _imageViews is (obviously) my array of images { if (CGRectIntersectsRect(contentFrame, imageView.frame)) { imageView.image = ... // set the image property } else { imageView.image = nil; } } } 

这是一些代码的片段,它正在做一些其他的东西,所以很明显你的实现会有很大不同,但它显示了如何使用scrollViewDidScroll来确定哪些图像是可见的并适当地加载/卸载图像。 如果你也想删除/添加UIImageView对象,你可能会进一步改变,但显然必须改变“这个imageview可见”的逻辑,而不是利用所有UIImageView对象的frame

我不确定我是否正确阅读你的代码,但你是否也将所有的UIImage对象都放在字典中? 这本身就非常奢侈地使用了内存。 我通常将实际图像保存在一些持久性存储中(例如,我使用Documents文件夹,但您可以使用Core DataSQLite ,尽管后两者对大图像的性能影响很大)。 我保留在内存中的唯一图像是UI主动使用的NSCache ,出于性能原因,我将使用NSCache对象来保留一些,但我将它们从持久存储中拉出来,而不是从活动内存中取出。

您应该使用滚动视图委派来确定当前时间屏幕上将显示哪些图像,并且只将这些图像加载到内存中。

此外,如果显示的图像尺寸远小于实际图像尺寸,则应调整图像大小并使用较小的图像。

为什么不使用UICollectionViewUICollectionViewController类? 这里是 UICollectionViewController引用

示例代码在这里 。

您的图像最终将成为UICollectionViewCell实例。 数据源和委托协议方法类似于UITableView方法。 即它们提供了一种机制, UICollectionViewController将重用UICollectionViewCells

使用这些类的好处是它们与UITableViewControllers类似地使用,它们可以帮助您解决您遇到的内存压力问题。

祝你好运!