Iphone 如何在Objective-C中实现事件驱动算法,类似于NSXMLParser

Iphone 如何在Objective-C中实现事件驱动算法,类似于NSXMLParser,iphone,objective-c,Iphone,Objective C,我想实现一个classX,它可以进行一些异步调用,但是在调用方ClassC看来,classX应该是顺序的 ClassC将实例化ClassX,它通过NSURLConnection进行一些HTTP调用,因此,它变得异步(我希望它保持异步) 逻辑如下: C类: - (void)callerWork { // shouldn't return until connection response completes // and receives all of the response

我想实现一个classX,它可以进行一些异步调用,但是在调用方ClassC看来,classX应该是顺序的

ClassC将实例化ClassX,它通过NSURLConnection进行一些HTTP调用,因此,它变得异步(我希望它保持异步)

逻辑如下:

C类:

- (void)callerWork
{
    // shouldn't return until connection response completes 
    // and receives all of the response data
    BOOL result = [classX doSomeWork]; 
}
类别X:

- (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的工作方式,调用它的“parse”方法,直到所有工作完成后才返回。为了处理数据,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];
}
做这件事的好方法是什么

我知道您需要让一个类作为另一个类的代理来进行回调
但是,您使用什么机制使“[parser parse]”不会立即返回?

您可以启动另一个线程来完成所有异步工作,并自行休眠,直到工作线程在完成时将其唤醒。但是,不要从主线程调用此方法,因为您不想在主UI线程中休眠。

新的运行循环仍必须位于classX方法调用之外的另一个线程中。