I am using NSURLConnection to download some JSON from a webservice, and then display in a UITableView. I have all the code working well in the view class, but I wondered if I could have the NSURLConnection methods available to other classes?
For example, something like the following:
NSURLConnectionClass *connection = [[NSURLConnectionClass alloc] init];
NSArray *myDataArray = [connection withURL: [NSURL URLWithString: @"http://www.example.com"]];
// Reload table with new data
I realise this wont work as NSURLConnection is asynchronous, but wondered if there was something else I could try. I’m basically trying to avoid repeating code in every view that downloads data.
You can create a delegate protocol for your custom connection class. This way it can download async and still and call back when done. Even better would be to use blocks for callbacks. This pattern is used in the popular ASIHttpRequest class.
You can even make this class the delegate and data source for the table view. This way you only have to call
[tableview reloadData]when done loading. Downside is that this mixes up the MVC pattern a bit.