我使用NSInvocationOperation
生成了一组异步调用:
- (void)listRequestQueue:(StoreDataListRequest *)request {
[openListRequests addObject:request];
NSInvocationOperation *requestOp = [[NSInvocationOperation alloc]
initWithTarget:self
selector:@selector(listRequestStart:)
object:request];
[opQueue addOperation:requestOp];
[requestOp release];
}
- (void)listRequestStart:(StoreDataListRequest *)request {
if(self.resourceData == nil) {
//TODO fail appropriately...
return;
}
StoreDataListResponse *response = [self newListResponseForProductID:request.productID];
[self performSelectorOnMainThread:@selector(listRequestFinish:)
withObject:response waitUntilDone:NO];
[response release];
[self performSelectorOnMainThread:@selector(cleanUpListRequest:)
withObject:request waitUntilDone:NO];
}
- (void)listRequestFinish:(StoreDataListResponse *)response {
[self.delegate storeData:self didReceiveListResponse:response];
}
- (StoreDataListResponse *)newListResponseForProductID:(NSString *)productID {
CollectionData *data = [self.resourceData dataForProduct:productID];
if(data == nil) {
//TODO do something
}
StoreDataListResponse *response = [[StoreDataListResponse alloc] init];
response.productID = productID;
if(productID != data.productID) {
//TODO fail; remove product from list
}
response.name = NSLocalizedString(@"Loading...", @"Loading message");
response.blurb = NSLocalizedString(@"Waiting for response from server", @"Waiting for website to respond");
return response;
}
对于上面代码中的每个TODO
,我应该解决问题并让任何处理程序知道事情已经失败以及原因。查看NSError
课程和文档,它似乎是合适的答案,但我无法弄清楚如何使用NSInvocationOperation
和performSelectorOnMainThread:withObject:waitUntilDone:
。我当然可以通过将NSError
方法更改为newListResponseForProductID:
方法来获取- (StoreDataListResponse *)newListResponseForProductID:(NSString *)productID error:(NSError **)error;
s:
{{1}}
如何将错误生成回主线程,以便处理失败的请求?
答案 0 :(得分:0)
在主线程上运行任何代码的最简单方法是在iOS 4及更高版本上使用GCD和块。像这样:
dispatch_async(dispatch_get_main_queue(), ^(void) {
// Your code to run on the main thread here,
// any variables in scope like NSError is captured.
});
如果您知道自己位于后台线程并希望在继续之前在主线程上完成该块,请使用dispatch_sync()
。