gpt4 book ai didi

ios - 保存或更新核心数据后不更新表 - Swift

转载 作者:行者123 更新时间:2023-11-28 07:21:38 24 4
gpt4 key购买 nike

我的项目中的 CRUD 有以下类:

class ProjectCoreDataStore: DegreesProtocol, DegreesStoreUtilityProtocol {

// MARK: - Managed object contexts
var mainManagedObjectContext: NSManagedObjectContext
var privateManagedObjectContext: NSManagedObjectContext

// MARK: - Object lifecycle

init()
{

//let fileName: String = "PortalMDBApp.sqlite"
let fileName: String = "MDB.sqlite"

let fileManager:FileManager = FileManager.default
let directory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!

let documentUrl = directory.appendingPathComponent(fileName)
let bundleUrl = Bundle.main.resourceURL?.appendingPathComponent(fileName)

// here check if file already exists on simulator
if fileManager.fileExists(atPath: (documentUrl.path)) {
//Document file exists!
//return documentUrl.path
}else if fileManager.fileExists(atPath: (bundleUrl?.path)!) {
//Document file does not exist, copy from bundle!
try! fileManager.copyItem(at:bundleUrl!, to:documentUrl)
}

// MARK: - After pass sqlite to device then run bellow code

// This resource is the same name as your xcdatamodeld contained in your project.
guard let modelURL = Bundle.main.url(forResource: "MDB", withExtension: "momd") else {
fatalError("Error loading model from bundle")
}

// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
fatalError("Error initializing mom from: \(modelURL)")
}

let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
mainManagedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
mainManagedObjectContext.persistentStoreCoordinator = psc

let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let docURL = urls[urls.endIndex-1]
/* The directory the application uses to store the Core Data store file.
This code uses a file named "DataModel.sqlite" in the application's documents directory.
*/
let storeURL = docURL.appendingPathComponent("MDB.sqlite")
do {
try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
} catch {
fatalError("Error migrating store: \(error)")
}

privateManagedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
privateManagedObjectContext.parent = mainManagedObjectContext
}

deinit
{
do {
try self.mainManagedObjectContext.save()
} catch {
fatalError("Error deinitializing main managed object context")
}
}

// MARK: - CRUD operations - Generic enum result type

func updateLanguageDB(idLang: String,
completionHandler: @escaping (() throws -> String) -> Void) {

privateManagedObjectContext.perform {
//MARK: Clear selectedLang
do {
let clears = NSFetchRequest<NSFetchRequestResult>(entityName: "ShortMajorTBL")
let query = NSPredicate(format: "(%K = %@)",
"identifier","L100")
clears.predicate = query
let results = try self.privateManagedObjectContext.fetch(clears)
let resultData = results as! [ShortMajorTBL]
for object in resultData {
object.isSelected = "false"
}
do {
try self.privateManagedObjectContext.save()
}catch{
}
completionHandler{return "SeuccesClear"}
} catch {
completionHandler { throw DegreesStoreError.CannotFetch("Cannot fetch orders") }
}

//MARK: Update selectedLang
do {
let updateRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ShortMajorTBL")
let query = NSPredicate(format: "(%K = %@) AND (%K = %@) AND (%K = %@)",
"isSelected","false",
"langId",idLang.uppercased(),
"identifier","L100")
updateRequest.predicate = query
let results = try self.privateManagedObjectContext.fetch(updateRequest)
let resultData = results as! [ShortMajorTBL]
for object in resultData {
object.isSelected = "true"
}
do {
try self.privateManagedObjectContext.save()
}catch{
}
completionHandler{return "SeuccesUpdate"}
} catch {
completionHandler { throw DegreesStoreError.CannotFetch("Cannot fetch orders") }
}
}
}


func fetchListSelectedLangShortTermDB(completionHandler: @escaping (() throws -> [ShortMajorTBL]) -> Void){
privateManagedObjectContext.perform {
do{
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ShortMajorTBL")
let query = NSPredicate(format: "(%K = %@) AND (%K = %@)",
"isSelected","true",
"identifier","L100")
fetchRequest.predicate = query
let results = try self.privateManagedObjectContext.fetch(fetchRequest) as! [ShortMajorTBL]
for ss in results{
print("1 >>> \(ss.idLang)")
}
}catch{
}

do{
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ShortMajorTBL")
let query = NSPredicate(format: "(%K = %@) AND (%K = %@)",
"isSelected","true",
"identifier","L100")
fetchRequest.predicate = query
let results = try self.privateManagedObjectContext.fetch(fetchRequest) as! [ShortMajorTBL]
for ss in results{
print("1 >>> \(ss.idLang)")
print("1 >>> \(ss.id)")
}
}catch{
}
}
}
}

问题: 我正在使用此 func updateLanguageDB 更新记录,当我在 func updateLanguageDB< 中使用以下 query 进行测试时 告诉我更新成功:

do{
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ShortMajorTBL")
let query = NSPredicate(format: "(%K = %@) AND (%K = %@)",
"isSelected","true",
"identifier","L100")
fetchRequest.predicate = query
let results = try self.privateManagedObjectContext.fetch(fetchRequest) as! [ShortMajorTBL]
for ss in results{
print("1 >>> \(ss.id)")
}
}catch{
}

但是当我在其他页面中使用上面的query 时没有得到任何结果??!!

这是我的乐趣:

func fetchListSelectedLangShortTermDB(completionHandler: @escaping (() throws -> [ShortMajorTBL]) -> Void){
privateManagedObjectContext.perform {
do{

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ShortMajorTBL")
let query = NSPredicate(format: "(%K = %@) AND (%K = %@)",
"isSelected","true",
"identifier","L100")
fetchRequest.predicate = query
let results = try self.privateManagedObjectContext.fetch(fetchRequest) as! [ShortMajorTBL]
print("1 ++++ \(results.count)")
for ss in results{
print("1 >>> \(ss.idLang)")
print("1 >>> \(ss.id)")
}
}catch{
}
}
}

这是我的 xcdatamodelddebug sqlite :

enter image description here

并且: enter image description here

并且:enter image description here

注意 当我从设备中获取我的 sqlite 时,我没有看到任何更新记录。

最佳答案

我删除了 privateManagedObjectContext 并仅使用 mainManagedObjectContext,现在干得不错。并从主要状态中删除了 Z_PK

关于ios - 保存或更新核心数据后不更新表 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57833135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com