次のコードは、さまざまなサイズのサーバーから 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];
}