我想实现一个进行一些异步调用的classX,但是在调用者ClassC的眼里,classX应该是连续的。
ClassC会实例化ClassX,它会通过NSURLConnection进行一些HTTP调用,因此,它就变成了异步的(我希望它保持异步)。
逻辑流程如下:
ClassC:
- (void)callerWork
{
// shouldn't return until connection response completes
// and receives all of the response data
BOOL result = [classX doSomeWork];
}ClassX:
- (void)doSomeWork
{
// With an NSURLRequest, initiates a NSURLConnection
// Only after all of the data is received (or error) from
// NSURLConnection via NSURLConnectionDelegate methods,
// return from this method
}
// Implements relevant NSURLConnectionDelegate methods
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{ }
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{ }
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{ }
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{ }
@end基本上,我想模仿NSXMLParser的工作方式,即调用它的“解析”方法,该方法在所有工作完成后才会返回。为了处理数据,NSXMLParser将调用相关的NSXMLParserDelegate方法,这些方法由调用类实现,如下所示:
- (void)parseWork
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:dataToParse];
[parser setDelegate:self];
// 'parse' method doesn't return right away - execution continues
// only after all of the data has been parsed, which means the delegate
// methods are getting called in the interim.
BOOL parseResult = [parser parse];
}有什么好方法可以做到这一点呢?
我知道您需要让一个类作为另一个类的回调委托,但是使用什么机制使“解析器解析”不会立即返回呢?
发布于 2010-08-26 10:08:58
您的classX方法可以启动另一个线程来完成所有异步工作,并自行休眠,直到辅助线程在完成时唤醒它。但是不要从主线程调用此方法,因为您不希望在主UI线程中休眠。
https://stackoverflow.com/questions/3569699
复制相似问题