问题描述
我尝试在Mac Catalyst上运行iOS应用程序,但是我的应用程序具有Core Data。我已经阅读了这篇文章:
Initializing CoreData in macOS
但是我没有实现它。我不知道...
我在使用Core Data的View Controller中编写此代码。这与AppDelegate.swift文件中存在的代码相同(我尚未删除)。
#if targetEnvironment(macCatalyst)
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "MyApp")
container.loadPersistentStores(completionHandler: { (storeDescription,error) in
if let error = error as NSError? {
print("Unresolved error \(error),\(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext() {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
print("Unresolved error \(nserror),\(nserror.userInfo)")
}
}
}
#endif
当我在Core Data中更新或插入数据时
// SAVE the context.
do {
try context.save()
} catch {
let nserror = error as NSError
print("Unresolved error \(nserror),\(nserror.userInfo)")
}
#if targetEnvironment(macCatalyst)
// SAVE the context.
self.saveContext()
#endif
我很失落。我需要知道如何编写代码。我知道这并不复杂,但是我迷路了。
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Topic")
fetchRequest.returnsObjectsAsFaults = false
let results = try? context.fetch(fetchRequest)
let newSelectedValue = string
if (results?.count)! > 0 {
for updateItem in results as! [NSManagedobject] {
updateItem.setValue(newSelectedValue,forKey: "topicName")
}
} else {
let newItem = Topic(context: context)
newItem.topicName = newSelectedValue
}
// SAVE the context.
do {
try context.save()
} catch {
let nserror = error as NSError
print("Unresolved error \(nserror),\(nserror.userInfo)")
}
解决方法
据我了解,您所阅读的帖子给您带来的困惑远不止于帮助您。它的建议是将Core Data代码从AppDelegate移至主要的ViewController,我个人对此表示反对。
使用Catalyst时,您可以对核心数据使用完全相同的代码。
所以我建议删除专门为macCatalyst编写的代码,并在同一位置加载iOS和macOS的PersistentStores。