我需要執行多個Web請求並希望它速度很快。數據量非常小,但服務器使用一段時間來回答,所以我正在考慮使用多個線程。問題是如何處理返回值。我不知道這是否工作:從多個線程收集返回值
- (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];
}
我不知道如果[self bookList]會處理這個?我應該使用一些鎖還是什麼?
編輯
我已經做了一些閱讀,不知道這是什麼,我需要做什麼?
NSLock * myLock = [[NSLock alloc] init];
-(void)findAuthorForBookDidFinishWithAuthor:(NSString *)authorName andBookID:(NSString *)bookID
{
[myLock lock];
[[self bookList]setValue:authorName forKey:bookID];
[myLock unlock];
}
PLS評論,不只是「減一」我即使我是一個完整的混蛋:-)減一沒有告訴我很多。 (除此之外,我很遠)