我有一个程序可以将 CSV 文件中的数据添加到核心数据中。将托管对象上下文保存到持久存储后,我想运行一个检查点以将 WAL 文件的内容刷新到 SQLite 文件中。我已将代码添加到我的类中以尝试这样做,但我无法在“sqlite3_wal_checkpoint(...)”行中确定在不安全指针参数中放置什么(在代码中用 ???????? 表示) ).当然,如果有更好的方法,请告诉我。
class UpdateCoreDataTest: ObservableObject {
@Published var isLoading: Bool = true
var moc: NSManagedObjectContext
init(moc: NSManagedObjectContext) {
self.moc = moc
Task {
await IsDataStoreEmpty(moc: self.moc)
let fund1 = CSVtoCoreData(fundName: "Fund1", fileName: "Fund1.csv")
let fund2 = CSVtoCoreData(fundName: "Fund2", fileName: "Fund2.csv")
let fund3 = CSVtoCoreData(fundName: "Fund3", fileName: "Fund3.csv")
await fund1.CSVtoCoreDataG(moc: self.moc)
await fund2.CSVtoCoreDataG(moc: self.moc)
await fund3.CSVtoCoreDataG(moc: self.moc)
do {
try moc.save()
} catch {
print("Error saving. \(error)")
}
//--- start of added code
let fileURL = URL(fileURLWithPath: "/Users/Chris/Downloads/Persistent Store 2/Funds.sqlite")
var dataBase: OpaquePointer?
if sqlite3_open(fileURL.path, &dataBase) != SQLITE_OK {
print("Unable to open sqlite file")
} else {
print("Succesfully opened sqlite file")
}
// sqlite3_wal_checkpoint(dataBase, ??????? )
sqlite3_close(dataBase)
//--- end of added code
DispatchQueue.main.async {
self.isLoading = false
}
}
} // end init
}
来自文档:
第二个参数是附加数据库的名称(或NULL)。如果 参数为 NULL 或指向零长度字符串,则 指定的操作在附加到的所有 WAL 数据库上尝试 数据库连接db.
但是,当数据库文件上的最后一个数据库连接关闭时,SQLite 将自动检查点,WAL 文件将被删除。所以如果你需要打开数据库来做检查点,那么可能根本就没有什么可做的。
我更多地考虑了你关于 SQLite 在数据库文件上的最后一个数据库连接关闭时自动运行检查点的声明。所以我删除了上面“添加代码开始”和“添加代码结束”之间的代码。我把代码放在下面。从协调器中删除持久存储似乎关闭了核心数据和磁盘文件之间的连接。执行这段代码后,将按照您的说明自动运行检查点。完美。
let persistentStore = persistentContainer.persistentStoreCoordinator.persistentStores.first
do {
try coreDataContainer.persistentStoreCoordinator.remove(persistentStore!)
} catch {
print("Unable to remove store -> \(error)")
}