Okay here is what I’m trying to do:
I have a model object that is populated by some network data, I want to be able to create it like this:
// createWithID will fire off a request to a server
MyObject *newObject = [MyObject createWithID:123];
if(newObject){
//do something!
}
The problem I’m having is the network call within the createWithID method is asynchronous, so the method will always return before the call is complete.
First, is this an okay way to do this? I like the idea of encapsulating the network call in the method. Second, can it be done without blocking the main thread?
Thanks!
To expand on @danh’s answer a bit, I’d say that you shouldn’t have a pointer to the object until after it’s all done. For example:
And then the creation method would be something like this:
In principle, I find that the safer you make the API, the less likely you’ll be to screw something up. This way is safe because you never have a pointer to a partially constructed
MyObject. There’s no way you could get one and have it not be fully ready to use. Granted there’s no cancellation mechanism, but you could still extend this to allow for that.