[英]iOS Memory issue (ARC) when downloading and saving large ammount of images from server
以下代碼從大小不同的服務器上下載了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];
}
根據您的屏幕截圖,我認為問題出在NSURL緩存而不是實際的NSData對象。 您可以嘗試以下方法:
在您的應用程序委托中,設置初始URL緩存:
- (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];
}
將創建一個緩存文件: "Library/Caches/your_app_id/nsurlcache"
Apple示例的鏈接在這里: URL緩存
代碼未經測試,但這(或類似的東西)應該可以解決您的問題+您還可以嘗試使用緩存大小。
您可以使用此代碼發布另一個實際分配屏幕截圖嗎? 我希望看到內存使用停止增長並趨於平穩。
“ dataWithContentsOfURL
”返回一個自動釋放的NSData對象, 通常直到運行循環結束或該方法結束時才釋放該對象,因此也就不足為奇了。
將其更改為顯式的“ initWithContentsOfURL
”方法,然后在絕對使用完圖像數據后通過執行“ data = nil;
”來強制釋放 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.