Merge data management seamlessly with UI. Model, persist, and update app data effortlessly using declarative syntax. Fetch, sort, and filter data effortlessly, ensuring a responsive and engaging user experience. Simplify synchronization between data and UI layers for efficient, scalable app development.
Let us understand the setup of Core Data in SwiftUI
Create Core Data Model
- Create new file of type Data Model under Core Data.
- Add entity by tapping on
+
button. Then add attributes. Your file will look like below after adding EmployeeModel with EmployeeEntity and name and id as attributes
Create Core View Model
This swift file will contain initialization and methods required to work core data.
Let us give a look on the code.
Initialization of Core Data
import CoreData
class EmployeeViewModel: ObservableObject {
var context: NSPersistentContainer
@Published var employeeEntity: [EmployeeEntity] = []
init(){
context = NSPersistentContainer(name: "EmployeeModel")
context.loadPersistentStores { description, error in
if let error = error {
print("error loading: \(error)")
}
}
}
}
Here, EmployeeModel is initialized using NSPersistentContainer.
Fetching Core Data
func fetchData() {
let request = NSFetchRequest<EmployeeEntity>(entityName: "EmployeeEntity")
do {
employeeEntity = try context.viewContext.fetch(request)
} catch (let error) {
print("error fetching: \(error)")
}
}
Adding data to Core Data Entity
func addData(name: String,
id: Int16) {
let newEmployee = EmployeeEntity(context: context.viewContext)
newEmployee.id = id
newEmployee.name = name
self.saveData()
}
Saving Core Data
func saveData() {
do {
try context.viewContext.save()
} catch (let error) {
print("error saving: \(error)")
}
}
Deleting data from Core Data
func deleteData(indexSet: IndexSet) {
guard let index = indexSet.first else { return }
let entity = employeeEntity[index]
context.viewContext.delete(entity)
self.saveData()
}
Using Core Data in swiftUI View
Create a @StateObject variable Viewmodel. Use the publised property of Core Data Entity to updae the UI. Publised property of Core Data Entity will work similarly as an data array. Data an be displayed by Using ForEach in stack (HStack or VStack) or List view can also be used to do so.
struct EmployeeView: View {
@StateObject var viewModel = EmployeeViewModel()
/// code
Feel free to refer my demo project on Core Data in SwiftUI coredata-swiftui