2

I try implement core data in my app. I can insert data and fetch data in emulator. I try print the data and the data is exist. But when i open sqlite file, the data is empty. It only have table and attribute but not have data. I using swift 3.

This is JobOrder.swift

import Foundation
import CoreData

public class JobOrder: NSManagedObject {

}

This is JobOrder+CoreDataProperties.swift

import Foundation
import CoreData

extension JobOrder {

@nonobjc public class func fetchRequest() -> NSFetchRequest<JobOrder> {
    return NSFetchRequest<JobOrder>(entityName: "JobOrder");
}

@NSManaged public var body: String?
@NSManaged public var id: Int64
@NSManaged public var orderID: Int64

 }

This the way i insert data

 func seedPerson(){

    let entity = NSEntityDescription.insertNewObject(forEntityName: "JobOrder", into: moc)

    entity.setValue("name", forKey: "body")

    do{
        try moc.save()
    }catch{
        fatalError("failed: \(error)")
    }
}

This the way i fetch data

func fetch(){
    let personFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "JobOrder")
    do{
        let fetchPerson = try moc.fetch(personFetch)
        print("bodyName \((fetchPerson.first! as AnyObject).body!))")
    }
    catch {
    }
}

For insert and fetch, it working but when open my sqlite file the data not exist.

This is my file DataController

import UIKit
import CoreData
class DataController: NSObject {
var managedObjectContext: NSManagedObjectContext
override init() {
    // This resource is the same name as your xcdatamodeld contained in your project.
    guard let modelURL = Bundle.main.url(forResource: "modeldb", 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)
    managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = psc

        let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let docURL = urls[urls.endIndex-1]

        //          let storeURL = docURL.URLByAppendingPathComponent("modeldb.sqlite")
        let storeURL = NSURL(string:"modeldb.sqlite", relativeTo:docURL)
        do {
            try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL as URL?, options: nil)
        } catch {
            fatalError("Error migrating store: \(error)")
        }
    }
}

This is my file modeldb.xcdatamodelid

i also got error in log

CoreData: warning: Unable to load class named 'JobOrder' for entity 'JobOrder'.  Class not found, using default NSManagedObject instead.
Fahim
  • 3,466
  • 1
  • 12
  • 18
MAS. John
  • 582
  • 6
  • 22
  • From where are you getting the SQLite file that you check to see if it has data? Did you find the location of the simulator data and get the SQLite from the simulator's document folder for your app? And if yes, are you sure that you have the right folder location? – Fahim Mar 23 '17 at 03:25
  • I put this code let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) print("URLhere \(urls[urls.count-1] as URL)") . I put in appdelegate. – MAS. John Mar 23 '17 at 03:30
  • Then , i got path. Then open and in folder have modeldb.sqlite, modeldb.sqlite-shm,modeldb.sqlite-wal.. Have 3 file .. – MAS. John Mar 23 '17 at 03:31
  • 1
    You are looking at the right file but I think the issue is that you are simply looking in just the sqlite file and not taking the WAL (Write Ahead Log) file into account. See this thread - http://stackoverflow.com/questions/18888943/data-not-being-saved-to-core-data – Fahim Mar 23 '17 at 03:45
  • Possible duplicate of [Data not being saved to core data](http://stackoverflow.com/questions/18888943/data-not-being-saved-to-core-data) – Fahim Mar 23 '17 at 03:45
  • @Fahim .. i see the link .. but i don't how to solve it – MAS. John Mar 23 '17 at 03:50
  • 1
    Basically, if your data appears in code - the data is indeed there in your file, but it's in the WAL file. You need an SQLite browser which knows about the WAL file and can browse that too. Or, you have to wait till the data gets transferred from the WAL file to your SQLite database. Hope that makes sense? – Fahim Mar 23 '17 at 03:52
  • Thanks .. but how about this link http://stackoverflow.com/questions/32396130/how-to-open-sqlite-wal – MAS. John Mar 23 '17 at 03:55
  • Not every answer gets everything correct? :D Read this thread - it explains WAL files more in detail - http://stackoverflow.com/questions/20969996/is-it-safe-to-delete-sqlites-wal-file – Fahim Mar 23 '17 at 03:58
  • Yes, u right. i try open WAL file using texteditor and i can set data. Thanks .. i just want make sure the data in database. But if u know tool can open wal file , u can share with me .. Thank @Fahim – MAS. John Mar 23 '17 at 04:01
  • Happy to help :) I believe you can disable WAL mode. So that might be the easiest way to go so that your data is not stuck in a WAL file. – Fahim Mar 23 '17 at 04:03
  • If u know how to disable WAL mode in swift 3 , can share with me.. I do search , mostly in objective c and i dont know objective c and my app in swift 3 – MAS. John Mar 23 '17 at 04:23
  • I've added the code necessary for disabling WAL mode as an answer - please modify the original question to indicate that this is what you were looking for, so that it helps others :) – Fahim Mar 23 '17 at 05:03

1 Answers1

3

Further discussion resulted in a question about how to turn off WAL mode in CoreData using Swift 3.0. So I'm adding the necessary code here as an answer so that others can benefit from it too:

let dict = [NSSQLitePragmasOption: ["journal_mode":"DELETE"]]
do {
    try coordinator.addPersistentStore(ofType:NSSQLiteStoreType, configurationName:nil, at:url, options:dict)
} catch {
    // Report error
    abort()
}

In the above, coordinator is an NSPersistentStoreCoordinator instance and url is a URL instance pointing to the location of the persistent store.

Fahim
  • 3,466
  • 1
  • 12
  • 18