iphone - iOS 中的 dispatch_async 内存问题

标签 iphone ios grand-central-dispatch

我有一个包含大约 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/

相关文章:

ios - 如何使用 UIActivityViewController 共享事件的不同项目?

iphone - 模态视图阻止其他 View 旋转

objective-c - 奇怪的 NSArray 错误

ios - GCD DISPATCH_QUEUE_SERIAL 它将以什么优先级运行?

ios - 如何在 IOS Delphi 上的 TWebbrowser 中设置用户代理

ios - SceneKit 中的场景渲染不正确

iphone - 将文本设置为自定义表格单元格标签时崩溃

multithreading - 是否有一种模式可以取消另一个调度队列上的 block ?

ios - 为什么并发队列的行为怪异?

iphone - iOS 中的图形音频播放器