开发者

How to do event-driven algorithm in Objective-C, similar to NSXMLParser

I want to implement a classX that makes some asynchronous calls but in the eyes of the caller ClassC, classX should seem sequential.

ClassC would instantiate ClassX which makes some HTTP calls through NSURLConnection and thus, it becomes asynchronous (and I want it to stay async).

The logic flows like this:

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

Basically, I want to mimic how NSXMLParser works in that you invoke its "parse" method which doesn't return until all of the work is done. To process the data, NSXMLParser will call the relevant NSXMLParserDelegate methods, implemented by the callin开发者_StackOverflowg class, like so:

- (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];
}

What's a good way to do this?

I know that you need to have one class serve as the delegate of the other for the callbacks but with what mechanism do you make the '[parser parse]' not return right away?


You classX method could start another thread to do all the async work and sleep itself until the worker thread wakes it on completion. Don't call this method from the main thread though, as you don't want to sleep in the main UI thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜