开发者

Improve my asyncronous request design

I would like some opinions on a design that i have. My app is starting to send an asynchronous request to get some JSON data and if that goes well i get to my callback method and then start some other asynchronous request for some data then in another callback i go on and on and i feel my code is getting to be like spaghetti code, i jump from one callback method to a request to another callback then request and so on, any ideas of an better design ?

Let me show some example code (not the real code but shows my point) :

-(void)startApp { //make an request and use callBackMethod to parse data }

-(void)callBackMethod { //parse data and check it, if ok go make next request and use CallBackMethod1 }

-(void)callBackMethod1 { //par开发者_StackOverflow社区se data and check it, if ok go make next request and use CallBackMethod2 }

-(void)callBackMethod2 { //parse data and check it, if ok go make next request and use CallBackMethod3 }

-(void)callBackMethod3 { //parse data }

You get the point. It's a mess after my opinion and i want to refactor the code to something more readable and easier to maintain. I heard about blocks. Not sure how/if that might make my design better.

donnib


Your asynchronous request design is fine, although you should use more descriptive method names. The example here is not really spaghetti code, it's just you're doing something somewhat complicated and the code structure necessarily reflects that.

An implementation using blocks would look something vaguely like this:

- (void)startApp {
    [self makeRequest:... completionHandler:^(NSData *data){
        // Parse data and check it, as in callBackMethod
        if (ok) [self makeRequest:... completionHandler:^(NSData *data){
            // Parse data and check it, as in callBackMethod1
            if (ok) [self makeRequest:... completionHandler:^(NSData *data){
                // Parse data and check it, as in callBackMethod2
                if (ok) [self makeRequest:... completionHandler:^(NSData *data){
                    // Parse data, as in callBackMethod3
                }];
            }];
        }];
    }];
}

Depending on the situation, that may or may not be easier to follow. Another alternative, if you control the web service you're querying and the "check" is amenable, is to have the web service do all the checking on its end and return all the data in one response instead of requiring all this back-and-forth.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜