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 :
- GUI event creates a call to a transaction layer (model).
- Transaction layer (model) creates a async call to the web service.
- Response received from web service, parsed by transaction layer (check for error). Push results into core data.
- 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
精彩评论