- Is there an easy way to add Core Data persistence into an already built SwiftUI app?
I've been working through various SwiftUI tutorials to build a very simple reminders/to-do app for myself for the past couple of months. The functionality works, but every time I close the app, I lose the list of tasks. So I started delving into data persistence.
What I found is that Core Data seems to be the preferred method; however, it seems like MOST of the tutorials on Core Data are in conjunction with UIKit. Any Core Data tutorials with SwiftUI usually start with the beginning of the project, creating the models in Core Data from the beginning - not trying to implement them on the backend.
- Is there a way to relate my already created "Task" struct to a Core Data model, such that I don't have to recreate everything? With an extension of Task maybe? Or an easy to way to copy my Task struct over to the Core Data model class/entity?
As a beginner, I'm probably approaching this completely wrong, so I'm happy to take a different approach if there's something more preferable.
import Foundation
import SwiftUI
struct Task: Identifiable, Hashable, Codable {
let id: UUID
var taskTitle: String
var taskNotes: String
var isTapped: Bool
init(id:UUID = UUID(), taskTitle:String, taskNotes:String = "", isTapped:Bool = false) {
self.id = id
self.taskTitle = taskTitle
self.taskNotes = taskNotes
self.isTapped = isTapped
}
}
extension Task {
struct Data {
var taskTitle:String = ""
var taskNotes:String = ""
var isTapped:Bool = false
}
var data: Data {
Data(taskTitle: taskTitle, taskNotes: taskNotes, isTapped: isTapped)
}
}
Leaving this for anyone else that might be searching:
After tinkering with Core Data for a while and trying to get it set up, I ended up scrapping Core Data and using the FileManager system. I'm sure there's drawbacks to going this route versus going the Core Data route, but I'm only trying to store two relatively small arrays (less than 50 items for sure, probably less than 10 items in most cases) and a lot of the sorting is done in the app itself. So, it seemed like the easiest solution for now, as I was able to implement it in a few hours using my existing structs.
I used this as my guide, and tweaked slightly for my use case: https://developer.apple.com/tutorials/app-dev-training/persisting-data
While this looked intimidating at first, I found it to be infinitely easier than figuring out Core Data. Just my experience, but wanted to share my experience for anybody who finds this in the future.