开发者

Best practice for coding async web service calls on iOS

I have an iPhone app that talks to a web services, and pulls data from the web service to the devices. Pushes the data into core data, and then updates the GUI.

The process of doing this is as follows :

  1. GUI event creates a call to a transaction layer (model).
  2. Transaction layer (model) creates a async call to the web service.
  3. Response received from web service, parsed by transaction layer (check for error). Push results into core data.
  4. Sends a notification (either error or non-error) for GUI to update.

I have a lot of these async calls, to refresh different parts of the data. And my GUI clients are subscribed to a number of these notifications.

What I am finding, is that the code on the GUI side is a bit confusing when I go back to debug. Because actions are triggered by notifications.

What I would really like to do is to have some type of wrapper function around items 2, 3 and 4. So that the code looks more stream lined.

if (![TransactionLayerModelClass getDataFromWebServerWrapper: args])开发者_如何学JAVA {
    // error actions
} else {
    // good actions
}

I am not even sure this is possible, and have not found any solutions in my googling. But if it is, I think it would significantly improve the readability of my code.


To write code that looks the way you'd want, you'd want to use blocks:

[TransactionLayerModelClass 
     getDataFromWebServerWrapper: args
     errorBlock:^(NSError* error)
        {
           // error actions
        }
     successBlock:^(NSData* data)
        {
           // good actions
        }];

Blocks are only available when targeting iOS 4 and above. They're very useful, and while they are easy to abuse and misuse, this is one of their ideal applications when implemented properly.

http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/00_Introduction.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜