CoreData不存储Swift 4 Xcode 9
问题描述:
对于我的生活我无法弄清楚为什么我没有得到任何保存到CoreData的东西。我在构建阶段添加了CoreData.framework,但在查看Model.sqlite时仍然没有任何结果。CoreData不存储Swift 4 Xcode 9
的AppDelegate
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Model")
container.loadPersistentStores(completionHandler: {
(storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
func saveContext() {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
然后在我MainViewController
var timer : Timer?
var distance = Measurement(value: 0, unit: UnitLength.meters)
var run: Run! //name of the entity
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
// ...
private func saveRun() {
print("saveRun")
let newRun = Run(context: context)
print("got past core data")
newRun.distance = distance.value
newRun.duration = Int16(seconds)
newRun.timestamp = Date()
for locations in locationList {
let locationObject = Location(context: context)
locationObject.timestamp = locations.timestamp
locationObject.latitude = locations.coordinate.latitude
locationObject.longitude = locations.coordinate.longitude
newRun.addToLocations(locationObject)
(UIApplication.shared.delegate as! AppDelegate).saveContext()
run = newRun
}
}
答
所以......我是个白痴。它与我发布的代码一起工作。拧紧是在我的代码中出现错误,不知道如何正确使用Liya。谢谢大家的帮助
@Francesco Deliro
有用的事情。我会记住这一点
感谢大家的帮助
答
核心数据预计将在单个线程上运行。尽管该线程不一定是主线程,但Core Data并不旨在从不同线程访问。
你应该叫'context.save()'然后工作 – Mannopson
原谅我的无知如我在这个真正的新但是,这不是什么有发生( UIApplication.shared.delegate as!AppDelegate).saveContext() –
有没有错误?只是数据没有被保存? – 3stud1ant3