【发布时间】:2014-06-06 11:13:44
【问题描述】:
我正在从服务器下载图像,这是我的代码。
-(void) DownloadImages
{
NSLog(@"Images count to download %lu",(unsigned long)[productID count]); // about 3000
if ([productID count] > 0)
{
// Document Directory
NSString *myDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
for (i = 0; i < [productID count]; i++)
{
@autoreleasepool // is this right of use autoreleasepool???
{
@autoreleasepool
{
[self performSelectorInBackground:@selector(UpdateUI) withObject:nil];
}
NSLog(@"image no %d", i);
NSString *imageURL = [NSString stringWithFormat:@"http://serverPath/%@/OnlineSale/images/products/%@img.jpg",clientSite,[productID objectAtIndex:i]];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]];
// Reference path
NSString *imagePath = [NSString stringWithFormat:@"%@/%@img.jpg",myDirectory,[productID objectAtIndex:i]];
NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 1.0f)];
[imageData writeToFile:imagePath atomically:YES];
}
}
NSLog(@"Downloading images completed...");
}
}
编辑:这是 UpdateUI 方法
-(void) UpdateUI
{
spinner.hidden = NO;
[spinner startAnimating];
progressCounter.hidden = NO;
status.text = @"Synchronising Product Images...";
progressCounter.text = [NSString stringWithFormat:@"%d / %lu", i,(unsigned long)[productID count]];
}
在处理这个时,当我在 simulator 中时,使用的最大内存是: 超过 1500 张图片下载。
但在 iPad 上进行测试,最大内存已达到 106.9 MB,并且应用程序在下载 500 张图像后崩溃并显示此消息:
屏幕显示此消息:
从过去两天开始,我就一直停留在这一点上,挠了挠头后找不到任何解决方案。请帮我解决这个问题..
编辑: 使用 autoreleasedpool 的方式对不对???
【问题讨论】:
-
当您使用
performSelectorInBackground时,您必须为后台线程设置自己的NSAutoreleasePool。如果不是,它会导致内存泄漏。这是不推荐的方式。您应该使用NSOperation和队列或 GCD 块来满足后台处理需求。 -
至于您观察到的差异,您应该始终依赖真实设备的内存/性能。模拟器在您的 mac 硬件上运行,并且不会 100% 复制设备行为。
-
@Amar 请你给我 NSAutoreleasePool 的想法。如何使用它。?在我使用 ARC 时是否有必要?
-
这种方法对吗?
标签: ios iphone memory-management ios7