views:

28

answers:

1

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 calling 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?

A: 

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.

hotpaw2
What about using NSRunLoop?
Justin Galzic
A new run loop would still have to be in another thread than the classX method call.
hotpaw2