保存或更新核心数据后不更新表-Swift [英] Not update Table after saving or updating Core data - Swift

查看:50
本文介绍了保存或更新核心数据后不更新表-Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我的 CRUD 具有波纹管类:

I have bellow class for my CRUD in my project:

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 说我更新成功:

Problem: I am using from this func updateLanguageDB for update records and when I test with bellow query in func updateLanguageDB say me that the update is success:

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 时,没有得到任何结果吗?!!

But when I use from above query in other page do't get me any result??!!

这是我的乐趣:

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{
        }
    }
}

这是我的 xcdatamodeld debug sqlite :

并且:

并且:

Notic 当我从设备中获取 sqlite 时,我看不到任何更新记录.

Notic When I fetch my sqlite from device I don't see any update record.

推荐答案

我删除了 privateManagedObjectContext ,仅从 mainManagedObjectContext 中使用,现在很好.并从主要状态中删除了 Z_PK .

I removed privateManagedObjectContext and just use from mainManagedObjectContext, good work now. And removed Z_PK from primary status.

这篇关于保存或更新核心数据后不更新表-Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆