注意:我正在使用 ARC。
我有一些代码向 http 服务器发出 1 个请求以获取文件列表(通过 JSON)。然后它将该列表解析为模型对象,用于将下载操作(用于下载该文件)添加到不同的 nsoperationqueue,然后一旦完成添加所有这些操作(队列开始暂停),它就会启动队列并等待在继续之前完成所有操作。(注意:这都是在后台线程上完成的,以免阻塞主线程)。
这是基本代码:
NSURLRequest* request = [NSURLRequest requestWithURL:parseServiceUrl];
AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
op.responseSerializer = [AFJSONResponseSerializer serializer];
[op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//NSLog(@"JSON: %@", responseObject);
// Parse JSON into model objects
NSNumber* results = [responseObject objectForKey:@"results"];
if ([results intValue] > 0)
{
dispatch_async(_processQueue, ^{
_totalFiles = [results intValue];
_timestamp = [responseObject objectForKey:@"timestamp"];
NSArray* files = [responseObject objectForKey:@"files"];
for (NSDictionary* fileDict in files)
{
DownloadableFile* file = [[DownloadableFile alloc] init];
file.file_id = [fileDict objectForKey:@"file_id"];
file.file_location = [fileDict objectForKey:@"file_location"];
file.timestamp = [fileDict objectForKey:@"timestamp"];
file.orderInQueue = [files indexOfObject:fileDict];
NSNumber* action = [fileDict objectForKey:@"action"];
if ([action intValue] >= 1)
{
if ([file.file_location.lastPathComponent.pathExtension isEqualToString:@""])
{
continue;
}
[self downloadSingleFile:file];
}
else // action == 0 so DELETE file if it exists
{
if ([[NSFileManager defaultManager] fileExistsAtPath:file.localPath])
{
NSError* error;
[[NSFileManager defaultManager] removeItemAtPath:file.localPath error:&error];
if (error)
{
NSLog(@"Error deleting file after given an Action of 0: %@: %@", file.file_location, error);
}
}
}
[self updateProgress:[files indexOfObject:fileDict] withTotal:[files count]];
}
dispatch_sync(dispatch_get_main_queue(), ^{
[_label setText:@"Syncing Files..."];
});
[_dlQueue setSuspended:NO];
[_dlQueue waitUntilAllOperationsAreFinished];
[SettingsManager sharedInstance].timestamp = _timestamp;
dispatch_async(dispatch_get_main_queue(), ^{
callback(nil);
});
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
callback(nil);
});
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
callback(error);
}];
[_parseQueue addOperation:op];
然后是 downloadSingleFile 方法:
- (void)downloadSingleFile:(DownloadableFile*)dfile
{
NSURLRequest* req = [NSURLRequest requestWithURL:dfile.downloadUrl];
AFHTTPRequestOperation* reqOper = [[AFHTTPRequestOperation alloc] initWithRequest:req];
reqOper.responseSerializer = [AFHTTPResponseSerializer serializer];
[reqOper setCompletionBlockWithSuccess:^(AFHTTPRequestOperation* op, id response)
{
__weak NSData* fileData = response;
NSError* error;
__weak DownloadableFile* file = dfile;
NSString* fullPath = [file.localPath substringToIndex:[file.localPath rangeOfString:file.localPath.lastPathComponent options:NSBackwardsSearch].location];
[[NSFileManager defaultManager] createDirectoryAtPath:fullPath withIntermediateDirectories:YES attributes:Nil error:&error];
if (error)
{
NSLog(@"Error creating directory path: %@: %@", fullPath, error);
}
else
{
error = nil;
[fileData writeToFile:file.localPath options:NSDataWritingFileProtectionComplete error:&error];
if (error)
{
NSLog(@"Error writing fileData for file: %@: %@", file.file_location, error);
}
}
[self updateProgress:file.orderInQueue withTotal:_totalFiles];
}
failure:^(AFHTTPRequestOperation* op, NSError* error)
{
[self updateProgress:dfile.orderInQueue withTotal:_totalFiles];
NSLog(@"Error downloading %@: %@", dfile.downloadUrl, error.localizedDescription);
}];
[_dlQueue addOperation:reqOper];
}
我看到的是随着更多文件的下载,内存会持续飙升。这就像 responseObject 甚至整个 completionBlock 都没有被放开。
我试过让 responseObject __weak 和 fileData 一样。我已经尝试添加一个自动释放池,并且我也尝试使实际的文件域对象 __weak 但内存仍在不断攀升。
我已经运行了 Instruments 并且没有看到任何泄漏,但它从来没有达到所有文件都已下载的地步,然后内存不足并出现大的“无法分配区域”错误。在查看分配时,我看到一堆 connection:didFinishLoading 和 connection:didReceiveData 方法,它们似乎永远不会被放弃。不过,我似乎无法进一步调试它。
我的问题:为什么内存不足?什么没有被释放,我怎样才能让它这样做?