core-data - Mac Catalyst CoreData 适用于 iOS 而不是 macOS
问题描述
我尝试在 Mac Catalyst 上运行 iOS 应用程序,但我的应用程序具有核心数据。我读过这篇文章:
但我没有实现它。我不知道...
我在使用 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)")
}
解决方案
据我了解,您阅读的帖子使您感到困惑,而不是帮助您。它的建议是将核心数据代码从 AppDelegate 移动到主 ViewController,我个人不同意这一点。
使用 Catalyst 时,您可以对 Core Data 使用完全相同的代码。
所以我的建议是删除你专门为 macCatalyst 编写的代码,并在同一个地方为 iOS 和 macOS 加载 PersistentStores。
推荐阅读
- lua - Lua 中有没有办法在不使用 io.popen 的情况下列出目录?
- javascript - 在调用渲染函数之前,我可以在哪个 React 生命周期方法中使用 `this`
- typescript - TypeScript 记录类型如何产生索引类型?
- mysql - 删除级联时外键约束无效
- erlang - 如何使用来自 erlang shell 的参数生成进程
- scala - Ammonite:如何使用 Ivy 依赖项中的另一个脚本?
- java - 在不使用数组的情况下查找列表中的两个最大数字
- matlab - 输入和目标具有不同数量的样本
- c# - 当在 ajax 方法中使用 FormData 时,Json 在空白页面上将“new {success = true }”作为字符串返回
- authentication - 加载任何网页时强制用户更改密码