dispatch_async memory problems in iOS
I have a loop of about 2000+ items I need to go through:
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];
}
}
});
}
This works great and my main thread is not blocked but my memory goes through the roof - how do I get it to be released? Once the queue is empty it drops but I need it to clear out as it is going along.
Although you are running the code in the background you are running all of the code in the background at the same time. As fast you are able to loop through the array you are creating a new ASIHttpRequest that will be trying to download and save data at the same time. You may want to move your loop inside of the dispatch_async
, or use an NSOperation
that does the same thing but limit the max concurrent operations on the NSOperationQueue
. If you move the loop inside of dispatch_async
to do one at a time remember to create an NSAutoreleasePool
locally and drain it periodically.
- Instead of getting an autoreleased
ASIHTTPRequest
, try to alloc ,init , release one. - Haven't tried it , but think about alternating async and sync calls (to the same thread, not the main one) , like having 20 async requests followed by one sync.. this trick could help.
精彩评论