gpt4 book ai didi

ios - CoreData 不保存 Swift 4 Xcode 9

转载 作者:行者123 更新时间:2023-11-30 12:02:53 25 4
gpt4 key购买 nike

我一生都无法弄清楚为什么我没有将任何内容保存到 CoreData。我在构建阶段添加了 CoreData.framework,但当我查看 Model.sqlite 时仍然没有任何内容。

应用程序委托(delegate)

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

很高兴知道。我会记住这一点

感谢大家的帮助

关于ios - CoreData 不保存 Swift 4 Xcode 9,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46996138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com