从内存中下载并保存大量图像时的iOS内存问题(ARC)

下面的代码从一个服务器下载700多个不同大小的图像,这里的问题是内存(甚至是ARC)从不被释放,最终出现内存警告,然后应用程序退出。 我试过@autoreleasepool在这个方法,似乎没有工作。 另外我试过在不同的地方停止for循环来查看内存是否在完成后被释放,但事实并非如此。

这个方法在for循环中被调用,并接收图像url和短名称。 已经在后台线程和主线程中尝试了相同的结果(内存明智)。

-(void)saveImage:(NSString*)image name:(NSString*)imageName{ int k = 0; for (int j = 0; j < [imageName length]; j++) { if ([imageName characterAtIndex:j] == '/') { k = j; } }if (k != 0) { imageName = [imageName substringFromIndex:k+1]; } NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", imageName]]; if ([fileManager fileExistsAtPath:fullPath]) { [fileManager removeItemAtPath:fullPath error:nil]; } NSURL *url = [NSURL URLWithString:image]; NSData *data = [[NSData alloc]initWithContentsOfURL:url]; NSLog(@"Saved: %d:%@", [fileManager createFileAtPath:fullPath contents:data attributes:nil], url); data = nil; } - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { int cacheSizeMemory = 4*1024*1024; // 4MB int cacheSizeDisk = 32*1024*1024; // 32MB NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"]; [NSURLCache setSharedURLCache:sharedCache]; self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil]; self.window.rootViewController = self.viewController; [[UIApplication sharedApplication] setStatusBarHidden:YES]; [self.window makeKeyAndVisible]; return YES; } - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { NSLog(@"mem warning, clearing cache"); [[NSURLCache sharedURLCache] removeAllCachedResponses]; } 

分配

根据你的截图,我认为问题是与NSURLcaching,而不是实际的NSData对象。 你可以尝试以下几点:

在您的应用程序委托中,设置一个初始URLcaching:

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Do initial setup int cacheSizeMemory = 16*1024*1024; // 16MB int cacheSizeDisk = 32*1024*1024; // 32MB NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"]; [NSURLCache setSharedURLCache:sharedCache]; // Finish the rest of your didFinishLaunchingWithOptions and head into the app proper } 

将以下内容添加到您的应用程序委托中:

 - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { [[NSURLCache sharedURLCache] removeAllCachedResponses]; } 

caching文件将被创build: "Library/Caches/your_app_id/nsurlcache"

链接到苹果的例子是在这里: URLcaching

代码没有testing,但这个(或类似的)应该sorting你的问题+加上你可以尝试caching大小。

你能用这个代码发布另一个分配的屏幕截图吗? 我希望看到内存使用停止增长和平坦。

dataWithContentsOfURL ”返回一个自动释放的NSData对象,并且通常在运行循环结束或方法结束之前不会释放 ,所以难怪你快速填充内存。

将其更改为显式的“ initWithContentsOfURL ”方法,然后在完全使用图像数据时通过执行“ data = nil;强制发布