I need to do multiple web requests and want it to be fast. The amount of data is very small, but the server uses some time to answer so I am thinking about using multiple threads. The problem is how to handle the return values. I don’t know if this works:
- (void)findAuthorsForBookIDs:(NSArray*)bookIDs
{
for (NSString* thisBookID in bookIDs)
{
[NSThread detachNewThreadSelector:@selector(findAuthorForBook:) toTarget:self withObject:thisBookID];
}
}
-(void)findAuthorForBook:(NSString*)thisBookID
{
NSString *downloadString = [NSString stringWithFormat:
@"http://somewebsite.com/Mediator?bookIDNo=%@",
thisBookID];
NSURL *downloadUrl = [NSURL URLWithString:downloadString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:downloadUrl];
NSError *error;
NSURLResponse *response;
NSData *urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
NSString *html2;
if (urlData)
{
html2 = [[NSString alloc] initWithData: urlData encoding: NSISOLatin1StringEncoding];
}
[self findAuthorForBookDidFinishWithAuthor:html2 andBookID:thisBookID];
}
-(void)findAuthorForBookDidFinishWithAuthor:(NSString *)authorName andBookID:(NSString *)bookID
{
[[self bookList]setValue:authorName forKey:bookID];
}
I do not know if the [self bookList] will handle this? Should I use some locks or something?
EDIT
I have done some reading and wonder if this is what I need to do?
NSLock *myLock = [[NSLock alloc]init];
-(void)findAuthorForBookDidFinishWithAuthor:(NSString *)authorName andBookID:(NSString *)bookID
{
[myLock lock];
[[self bookList]setValue:authorName forKey:bookID];
[myLock unlock];
}
Pls comment, don’t just ‘minus one’ me even if I’m a complete jerk 🙂 Minus one doesn’t tell me much. (Other than that I’m far out)
There is no performance benefit to doing this with threads rather than
NSURLConnection. You can open multiple simultaneous requests without threads. Typically, however, the latency is connecting to the server is the biggest performance obstacle on mobile devices. If you can keep a single connection up, things will go faster.NSURLConnectionwill do some of this automatically using HTTP/1.1 connections if you let it (i.e. if you don’t fight it by doing your own threading). Opening many simultaneous connections is unlikely to help you very much, however, unless the server is extremely slow to respond to each one but is still capable to processing many in parallel (this is a very rare situation).You may also look at MKNetworkKit, which includes several tools for helping you manage simultaneous requests.