以下代码从服务器下载 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 示例的链接如下:网址缓存 https://developer.apple.com/library/ios/#samplecode/URLCache/Introduction/Intro.html
代码未经过测试,但这(或类似的东西)应该可以解决您的问题+此外您可以尝试缓存大小。
您可以发布另一个使用此代码进行分配的屏幕截图吗?我预计内存使用量会停止增长并趋于平稳。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)