简体   繁体   English

在哪里存储与 iOS 的 SQLite DB 连接?

[英]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.我用SQLite.swift创建了一个 SQLite 连接,但我不确定在哪里存储数据库连接,因此我可以在用户拥有各种视图的应用程序持续时间内使用它。

Is using UserDefaults here an appropriate case?在这里使用UserDefaults是否合适? Or EnvironmentObject ?还是EnvironmentObject

What is the recommendation with iOS apps in terms of keeping a DB connection open for reuse? iOS 应用程序在保持数据库连接打开以供重用方面的建议是什么?

Is using UserDefaults here an appropriate case?在这里使用 UserDefaults 是否合适?

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.而 UserDefaults 用于在应用程序未运行时要存储的内容。

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.可以,但从语义上讲它仍然是错误的:Apple 将其定义为“由父视图或祖先视图提供的可观察 object 的属性包装器类型。”,这并不真正适合数据库连接。 It's not an observable object with states.它不是带有状态的可观察 object。

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. View 与某种“数据提供者”接口进行对话,该接口定义了一个接口,无论数据存储在哪里,视图都可以通过该接口获取数据。
  • 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).而且您的视图实际上将使用 Observable 对象,除了那些可观察对象是数据本身,而不是与数据库的连接(实际上视图不会“知道”数据来自哪里)。

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.我不会 go 详细介绍如何使 model 发生 - 这里还有许多其他细节(比如你的应用程序的整体架构是什么),但这是这个想法的要点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM