I was wondering if anyone out there has general tips for how to structure an iOS app backed by a REST api. There are basically two approaches to this that I've thought of
API calls placed ad hoc in the view controllers.
In this approach the view controller has some state that it fetches from the backend such as a User object and then it renders that User's profile. This approach is simple in that you don't have to deal with any synchronization. You just fetch data when you need it, as if you were rendering a web page.
The downsides of this approach are twofold:
- Race conditions in viewing / updating models
- Synchronization problems with instances of models in other view controllers
To illustrate the first point, let's say you have some notification counts on the user profile. When you visit the profile page you fetch the user object but you also want to update the user when they visit a particular tab. So you have two calls:
GET /rest/user # gets the user POST /rest/user # clears notifications
The result is a race condition between fetching the user and updating the notification count. You may fetch a user object without the notifs cleared.
For the second point, you might update the user object but then have other view controllers which depend on the updated user object. Somehow you need to communicate the update to these view controllers.
Treat the app as a cache with a data store that syncs to the API
In this approach all model updates and fetches happen locally via a data interface. The data interface decides when to synchronize itself to the backend and, if it doesn't have some data locally, it blocks callers until the data is available. The downside of this approach is that it's more complicated, you have to deal with cache invalidation, and it's not clear to me how to implement the synchronization.
I want to go this route, but I'm not sure how to proceed. So, I have some questions:
- Does this data store seem like the right approach?
- Are there libraries that implement a data store like this? Or examples of projects that go this route?
- View controllers may fetch instances of objects through the data store, but then these view controllers still need to be aware of communicated updates somehow and I'm not sure how to communicate those updates.