iosswiftsqlite.swift

Where to store a SQLite DB connection with iOS?


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?


Solution

  • 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.

    So what you really want is

    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.