这个问题彻底难倒了我。这适用于带有 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)