Efficiency of Google Geocoding with Dispatch Queue - How to Improve - iPhone

别来无恙 提交于 2019-12-06 09:05:46

GCD is great but you should never use threading techniques if the SDK already offers an asynchronous API for this. In your case, never use stringWithContentsOfURL: as it is a synchronous & blocking code (which is probably why you switch to using GCD to make it in the background) while NSURLConnection has an asynchronous API. always use this asynchrounous API instead when you need to do any network request.

This is better for many reasons:

  • one being that it's an API already designed for this in the SDK (even if you will probably need to create a class like MyGeocoder that sends the request, handle the response, parse it, and return the value in an asynchronous way)
  • but the most significant reason to prefer the asynchronous API (over using the synchronous stringWithContentsOfURL + GCD) is that NSURLConnection is integrated with the NSRunLoop and schedules the retrieval of the socket data on the runloop, avoiding to create a lot of useless threads for that (and threads are evil if you use it where it is not strictly needed).
  • And finally, as NSURLConnection lifecycle is handled by the RunLoop itself, the delegate methods are already called on the main thread.

GCD is always better than using NSThreads directly, but using Runloop scheduling for things that are already made for in the SDK, especially NSURLConnections is always better both for performance (avoid thread scheduling issues), multithreading issues and much more.


[EDIT] For example if you don't want to implement the class yourself, you can use my sample OHURLLoader class and use it this way:

NSString* urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv", [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL* url = [NSURL URLWithString:urlString];
NSURLRequest* req = [NSURLRequest requestWithURL:url];

OHURLLoader* loader = [OHURLLoader URLLoaderWithRequest:req];
[loader startRequestWithCompletion:^(NSData* receivedData, NSInteger httpStatusCode) {
    NSString* locationString = loader.receivedString;
    NSArray *listItems = [locationString componentsSeparatedByString:@","];
    ... etc ...
    // this callback / block is executed on the main thread so no problem to write this here
    [mapViewLink addAnnotation:annotation];
} errorHandler:^(NSError *error) {
    NSLog(@"Error while downloading %@: %@",url,error);
}];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!