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{
}
}
}
}
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{
}
But when I use from above query
in other page do't get me any result??!!
And here is my fun
:
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{
}
}
}
Here is my xcdatamodeld
and debug sqlite
:
Notic When I fetch my sqlite
from device I don't see any update record.
I removed privateManagedObjectContext
and just use from mainManagedObjectContext
, good work now. And removed Z_PK
from primary status.