3

这个问题彻底难倒了我。这适用于带有 Xcode 4.2 的 iOS 5.0

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

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

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

[button1AImgVw setImage:image];

如果我注释掉该代码。所有编译都很好,没有发生内存错误。但是,如果我不注释掉该代码,我会收到内存错误并最终崩溃。另请注意,它确实处理了整个 CreateViews IBAction,但最终仍会崩溃。因为我在 iOS 5.0 和 Xcode 4.2 上运行它,所以我不能做 release 或 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)
4

1 回答 1

11

在我的 iOS 编程生涯中,这种情况(尝试将多个全分辨率 UIImage 加载到视图中时出现内存警告和应用程序退出)曾多次让我感到痛苦。

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

对于我自己的代码,我使用“ UIImage+Resize”类别,可以在此处找到详细信息

在插入视图之前将图像调整为更小的尺寸,然后确保释放全分辨率图像(或者如果在 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];
}
于 2012-10-07T21:45:18.203 回答