在setimage上收到内存警告

这个问题已经让我难住了。 这是iOS 5.0与Xcode 4.2

发生什么事是在我的应用程序,我让用户从他们的相册中select图像,我将这些图像保存到应用程序文档目录。 非常直截了当。

我所做的是在viewController.m文件之一中创build多个UIImageView,然后从用户从应用程序目录中select的图片之一设置图像视图的图像。 问题是,在一定数量的UIImage集合后,我收到“收到的内存警告”。 它通常发生在有10张照片时。 如果让我们说用户select了11张图片,那么应用程序崩溃与错误(GBC)。 注意:这些图像中的每一个至less有2.5 MB一块。

经过几个小时的testing,我终于把这个问题缩小到这行代码

[button1AImgVw setImage:image]; 

如果我注释掉这个代码。 所有编译好,没有发生内存错误。 但是,如果我不注释掉代码,我收到内存错误,最终崩溃。 还要注意,它处理整个CreateViews IBAction,但仍然崩溃在最后。 我不能做释放或dealloc,因为我在iOS 5.0上运行这个与Xcode 4.2

这是我使用的代码。 谁能告诉我我做错了什么?

 - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self CreateViews]; } -(IBAction) CreateViews { paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask ,YES); documentsPath = [paths objectAtIndex:0]; //here 15 is for testing purposes for (int i = 0; i < 15; i++) { //Lets not get bogged down here. The problem is not here UIImageView *button1AImgVw = [[UIImageView alloc] initWithFrame:CGRectMake(10*i, 10, 10, 10)]; [self.view addSubview:button1AImgVw]; NSMutableString *picStr1a = [[NSMutableString alloc] init]; NSString *dataFile1a = [[NSString alloc] init]; picStr1a = [NSMutableString stringWithFormat:@"%d.jpg", i]; dataFile1a = [documentsPath stringByAppendingPathComponent:picStr1a]; NSData *potraitImgData1a =[[NSData alloc] initWithContentsOfFile:dataFile1a]; UIImage *image = [[UIImage alloc] initWithData:potraitImgData1a]; // This is causing my app to crash if I load more than 10 images! // [button1AImgVw setImage:image]; //If I change this code to a static image. That works too without any memory problem. button1AImgVw.image = [UIImage imageNamed:@"mark-yes.png"]; // this image is less than 100KB } NSLog(@"It went to END!"); } 

这是我select10张图片时得到的错误。 应用程序确实启动和工作

 2012-10-07 17:12:51.483 ABC-APP[7548:707] It went to END! 2012-10-07 17:12:51.483 ABC-APP [7531:707] Received memory warning. 

当有11个图像时,应用程序崩溃与此错误

 2012-10-07 17:30:26.339 ABC-APP[7548:707] It went to END! (gbc) 

这种情况(内存警告和应用程序退出时,试图加载多个全分辨率UIImages到一个视图)试图烧我几次在我的iOS编程生涯。

在执行“ setImage ”调用之前,您需要制作原始图像的缩小副本。

对于我自己的代码,我使用“ UIImage+Resize ”类别, 其细节可以在这里find 。

在插入视图之前,将图像的大小调整为较小的值,然后确保全分辨率图像被释放(如果在ARC上,则将其设置为零),并且应该有更快乐的时间。

下面是我在自己的代码中做的事情:

 CGSize buttonSize = CGSizeMake(width, height); // it'd be nice if UIImage took a file URL, huh? UIImage * newImage = [[UIImage alloc] initWithContentsOfFile: pathToImage]; if(newImage) { // this "resizedimage" image is what you want to pass to setImage UIImage * resizedImage = [newImage resizedImage: buttonSize interpolationQuality: kCGInterpolationLow]; }