Reputation: 557
I'm cleaning up some of my code, and I decided to make a "backend" class to help with this. All this class does is fetch some data from a URL asynchronously, then call a parse method on the main thread when it's finished. When all is finished, I'm just writing a string from the parsed data to a UILabel
I've placed using interface builder. This works when all is contained in the ViewController.h/m, but it's cluttered and messy. I've taken all of the methods contained in the view controller and recreated them as class methods for my class so that all I have to do is call [Backend fetchData]
, etc.
However, I've run into a problem. I've realized that I don't actually know how to change the UILabel
's text field from anywhere but the view controller class itself. I've tried passing the UILabel
to the backend class, but I'm guessing the way I've done it isn't correct as it isn't working. Is what I'm trying to do possible/How can I accomplish it?
Upvotes: 1
Views: 133
Reputation: 57040
Create a block-based API.
[Backend fetchDataWithCompletionHandler: ^ (NSString* result, NSError* error)
{
if(error)
{
NSLog(@"Got error: %@", error);
return;
}
self.label.text = result;
}];
This is very versatile, and your view controller remains in control of its properties.
Ensuring thread-correctness can either be accomplished on the backend side (calling the completion handler on the main thread) of in block (checking if main thread, executing on main thread if not), but remember to assure it, so you don't end up updating the UI from a background thread.
Upvotes: 3