I try to run the iOS app on Mac Catalyst, but my app has Core Data. I have read this post:
Initializing CoreData in macOS
But I do not achieve to implement it. I don't know...
I write this code in a View Controller where a use Core Data. It is the same code that exists in AppDelegate.swift file (I haven't deleted it).
#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
And when I update or insert data in 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
I am very lost. I need to know how to write the code. I know that it is not complicated, but I am lost.
I SHOW THE CODE I USE TO READ/WRITE Core Data.
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)")
}