Home > Software design >  Where to store a SQLite DB connection with iOS?
Where to store a SQLite DB connection with iOS?

Time:11-19

I create a SQLite connection with SQLite.swift but I'm not sure where to store the DB connection so I can use it during the duration that a user has the app open across various views.

Is using UserDefaults here an appropriate case? Or EnvironmentObject?

What is the recommendation with iOS apps in terms of keeping a DB connection open for reuse?

CodePudding user response:

Is using UserDefaults here an appropriate case?

Definitely not. Like you said yourself: you want it to exist while the app is open. While UserDefaults is for things you want to store when app is not running.

Or EnvironmentObject?

You could, but semantically it's still wrong: Apple defines it as "A property wrapper type for an observable object supplied by a parent or ancestor view.", which doesn't really fit the DB connection. It's not an observable object with states.

Ideally you step back and look at a more generic architecture of your app.

  • Views want data in a specific format. They don't care where the data is coming from.
  • The fact that data is coming from DB is an implementation detail - tomorrow you may decide to retrieve it from remote server, and you don't want to change every single view because of that.

So what you really want is

  • View talks to some sort of "data provider" interface that defines an interface by which views can get their data regardless of where it's stored.
  • Your implementation of "data provider" is to talk to the local database (currently, but it can changed base don your needs).

In this structure the DB connection(s) are managed by data provider, and do not need to be shared with anyone. And your views will actually use Observable objects, except those observable objects are data itself, not the connection to database (and in fact views will not "know" where the data is coming from).

I will not go into details on how to make that model happen - there are many other details here (like what's overall architecture of your app), but this is the gist of the idea.

  • Related