CoreData — the easy way

UserList CoreData App
Create UserLIst
UserList.xcdatamodeld
import CoreData

public class PersistentContainer: NSPersistentContainer {}

public class CoreDataStack {

public let persistentContainer: NSPersistentContainer

public init() {
persistentContainer = PersistentContainer(name: "UserList")

persistentContainer.loadPersistentStores(completionHandler: { description, error in
if let error = error {
fatalError("Core Data store failed to load with error: \(error)")
}
})
}
}

public extension CoreDataStack {
func saveUser(named name: String) {
let user = User(context: persistentContainer.viewContext)
user.name = name

do {
try persistentContainer.viewContext.save()
print("User saved succesfully")
} catch {
persistentContainer.viewContext.rollback()
print("Failed to save movie: \(error)")
}
}
}

public extension CoreDataStack {
func getAllUsers() -> [User] {
let fetchRequest: NSFetchRequest<User> = User.fetchRequest()

do {
return try persistentContainer.viewContext.fetch(fetchRequest)
} catch {
print("Failed to fetch movies: \(error)")
return []
}
}
}

public extension CoreDataStack {
func deleteUser(_ user: User) {
persistentContainer.viewContext.delete(user)

do {
try persistentContainer.viewContext.save()
} catch {
persistentContainer.viewContext.rollback()
print("Failed to save context: \(error)")
}
}

func updateUser(_ user: User) {
do {
try persistentContainer.viewContext.save()
} catch {
persistentContainer.viewContext.rollback()
print("Failed to save context: \(error)")
}
}
}
import SwiftUI

@main
struct UserListApp: App {

var body: some Scene {
WindowGroup {
ContentView(coreDataStack: CoreDataStack())
}
}
}
import SwiftUI
import CoreData

struct ContentView: View {
let coreDataStack: CoreDataStack

@State var userName = ""
@State var users : [User] = []

var body: some View {
VStack {
Text("Add a user")
.font(.title)
.padding()

HStack {
TextField("Type user name", text: $userName)

Button("Save user") {
coreDataStack.saveUser(named: userName)
users = coreDataStack.getAllUsers()
}

Spacer()

}.padding()

List {
ForEach(users) { (user: User) in
Text(user.name ?? "")
}.onDelete { rows in
for row in rows {
let user = users[row]
coreDataStack.deleteUser(user)
}

users.remove(atOffsets: rows)
}
}.onAppear {
users = coreDataStack.getAllUsers()
}
}.padding()
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(coreDataStack: CoreDataStack())
}
}

Swift (iOS, iPadOS & macOS) Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store