Idea for Networking and Model Objects

I’m considering how to handle a pretty big refactoring of how networking code is handled in this app, and after talking to my friend about how he’s handling networking/model object creation in an app he’s working on if the way I’m thinking is a good idea or not.

What my friend described is that he’s using the active record pattern, which roughly translates here to sticking everything into the model, and creating new NSURLSession objects as needed. I don’t like the idea of needing to create a session object for every request, since the nice thing about NSURLSession is that all of your requests get to share a delegate, which minimizes repeated code in a lot of cases. I also had an assumption that NSURLSession has some smarts about managing its own queue of tasks and that creating separate session objects would mess that up. The other thing is that if you had some shared code specific to the service you were talking to, having all of your model objects manage all of their own networking seemed like a good way you might end up with some repeated code later on.

All of that aside, I do kind of like talking directly to the model objects when I need to get things done with them. It feels pretty natural that if you need to do something with SomeObject that you’d talk directly to it. The solution I’m thinking of is to borrow from Core Data and create a class that’s sort of like an NSManagedObjectContext which manages an NSURLSession and which I dependency inject as needed. It also gives me a nice place to stick things which are common to the service, so that code doesn’t get repeated across model classes.

For a service called Foo whose API I need to interact with to create Bar model objects by ID, I might have a class called ALBFooAPIContext and do something like this:

That method could then talk to the context object however it needs to in order to get stuff done. Is this a terrible idea? I’d probably go for calling the context class something else, except I think it’d be a good place to store stuff that is actual contextual to how I’m talking to the service (maybe a currentUser property).