微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Mac Catalyst CoreData可以在iOS上而不是macOS上运行

如何解决Mac Catalyst CoreData可以在iOS上而不是macOS上运行

我尝试在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。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。