我尝试在我的应用中实现核心数据。我可以在模拟器中插入数据和获取数据。我尝试打印数据,数据存在。但是当我打开sqlite文件时,数据是空的。它只有表和属性但没有数据。我使用swift 3。
这是JobOrder.swift
import Foundation
import CoreData
public class JobOrder: NSManagedObject {
}
这是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
}
这是我插入数据的方式
func seedPerson(){
let entity = NSEntityDescription.insertNewObject(forEntityName: "JobOrder", into: moc)
entity.setValue("name", forKey: "body")
do{
try moc.save()
}catch{
fatalError("failed: \(error)")
}
}
这是我获取数据的方式
func fetch(){
let personFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "JobOrder")
do{
let fetchPerson = try moc.fetch(personFetch)
print("bodyName \((fetchPerson.first! as AnyObject).body!))")
}
catch {
}
}
对于insert和fetch,它工作但是当打开我的sqlite文件时,数据不存在。
这是我的文件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)")
}
}
}
我在日志中也有错误
CoreData: warning: Unable to load class named 'JobOrder' for entity 'JobOrder'. Class not found, using default NSManagedObject instead.
答案 0 :(得分:3)
进一步的讨论导致了一个关于如何使用Swift 3.0关闭CoreData中的WAL模式的问题。所以我在这里添加必要的代码作为答案,以便其他人也可以从中受益:
let dict = [NSSQLitePragmasOption: ["journal_mode":"DELETE"]]
do {
try coordinator.addPersistentStore(ofType:NSSQLiteStoreType, configurationName:nil, at:url, options:dict)
} catch {
// Report error
abort()
}
在上文中,coordinator
是NSPersistentStoreCoordinator
实例,url
是指向持久存储位置的URL
实例。