我有一个包含大约 2000 多个项目的循环:
for (NSDictionary* dict in array) {
NSString *fileName = [NSString stringWithFormat:@"%@/%@_lg.jpg?t=",manufacturerID, [[dict valueForKey:@"ItemID"] stringByReplacingOccurrencesOfString:@" " withString:@"%20"]];
NSString *savePath = [documentsPath stringByAppendingPathComponent:fileName];
NSURL *url = [NSURL URLWithString: [[NSString stringWithFormat:kProductImagesURL, fileName]stringByAppendingString:lastImagesSyncDate]];
dispatch_queue_t aQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
dispatch_async(aQueue, ^{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
int statusCode = [request responseStatusCode];
if (statusCode==200) {
NSData *responseData = [request responseData];
[responseData writeToFile:[savePath stringByReplacingOccurrencesOfString:@"%20" withString:@" "] atomically:YES];
}
}
});
}
这很好用,我的主线程没有被阻塞,但我的内存力爆棚了——我该如何释放它?一旦队列为空,它就会消失,但我需要它在进行过程中被清除。
最佳答案
尽管您在后台运行代码,但您同时在后台运行所有 代码。您可以尽可能快地遍历数组,您正在创建一个新的 ASIHttpRequest,它将尝试同时下载和保存数据。您可能希望将循环移动到 dispatch_async
内部,或使用 NSOperation
它做同样的事情但限制了 NSOperationQueue
上的最大并发操作.如果您将循环移动到 dispatch_async
中以一次执行一个,请记住创建一个 NSAutoreleasePool
局部并定期排出。
关于iphone - iOS 中的 dispatch_async 内存问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6508693/