首页 > 解决方案 > Mac Catalyst CoreData 适用于 iOS 而不是 macOS

问题描述

我尝试在 Mac Catalyst 上运行 iOS 应用程序,但我的应用程序具有核心数据。我读过这篇文章:

在 macOS 中初始化 CoreData

但我没有实现它。我不知道...

我在使用 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-datamac-catalyst

解决方案


据我了解,您阅读的帖子使您感到困惑,而不是帮助您。它的建议是将核心数据代码从 AppDelegate 移动到主 ViewController,我个人不同意这一点。

使用 Catalyst 时,您可以对 Core Data 使用完全相同的代码。

所以我的建议是删除你专门为 macCatalyst 编写的代码,并在同一个地方为 iOS 和 macOS 加载 PersistentStores。


推荐阅读