在setimage上收到内存警告

时间:2012-10-07 21:36:00

标签: iphone ios xcode ipad ios5

这个问题让我完全不知所措。这适用于带有Xcode 4.2的iOS 5.0

在我的应用程序中,我让用户从他们的相册中选择图像,然后将这些图像保存到应用程序文档目录中。很直接。

我所做的是在viewController.m文件中的一个我创建多个UIImageViews然后我从用户从apps目录中选择的图片之一设置图像视图的图像。问题是在经过一定数量的UIImage设置后,我收到了“收到内存警告”。通常在有10张照片时发生。如果让我们说用户选择了11张图片,则应用程序会因错误(GBC)而崩溃。注意:每个图像至少2.5 MB一件。

经过数小时的测试后,我终于将问题缩小到这行代码

[button1AImgVw setImage:image];

如果我注释掉那段代码。所有编译都很好,没有内存错误发生。但是,如果我没有注释掉那些代码,我会收到内存错误并最终导致崩溃。还要注意它确实处理整个CreateViews IBAction但最后仍然崩溃。因为我在带有Xcode 4.2的iOS 5.0上运行它,所以我无法发布或dealloc

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

- (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!");

    }

这是我选择10张图像时出现的错误。应用程序确实启动并运行

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)

1 个答案:

答案 0 :(得分:11)

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

在进行“setImage”通话之前,您需要制作原始图像的缩小版本。

对于我自己的代码,我使用“UIImage+Resize”类别the details for which can be found here

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

以下是我在自己的代码中执行此操作的方法:

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];
}
相关问题