How do you use SwiftUI TextField with Core Data

Greetings,


I cannot figure out how to use Core Data and SwiftUI for all CRUD operations. I have yet to find an app tutorial or book that explains how to do something as simple as using a TextFiled to update a field like "title" for an entity like "Book". I thought I was close with the wrappedTitle that would return a String instead of a String? , but I still cannot crack this. I am a rookie.. but I have been searching the world on how to do this. Seems like a simple thing... Please help


import Foundation
import CoreData


extension Book {
    @nonobjc public class func fetchRequest() -> NSFetchRequest<Book> {
        return NSFetchRequest<Book>(entityName: "Book")
    }

    @NSManaged public var author: String?
    @NSManaged public var genre: String?
    @NSManaged public var id: UUID?
    @NSManaged public var rating: Int16
    @NSManaged public var review: String?
    @NSManaged public var title: String?

    public var wrappedTitle: String {
        title ?? "None"
    }

}

===========================================================================================
struct EditBook: View {
    @Environment(\.presentationMode) var presentationMode
    @Environment(\.managedObjectContext) var moc

    static let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)

    let book: Book
    @State var newTitle = "New Title"
    @State var newAuthor = "New Author"

    var body: some View {
        VStack {
         
            Form {
                Section {
                    TextField("Title", text: book.wrappedTitle). 
// ERROR Cannot convert value of type 'Binding<String?>' to expected argument type 'Binding<String>'
//Cannot convert value of type 'String' to expected argument type 'Binding<String>'
                }
            }
         
                Text("Edit This")
            Button(action: {
                // your action here
                self.book.title = self.newTitle
                self.book.author = self.newAuthor
                try? self.moc.save()
                self.presentationMode.wrappedValue.dismiss()

            }){
             
            Text("Done")
        }

        }
    }

}

Replies

It's six months too late, but here's two potential approaches:

(a) extend Bindings to have an eavesdropping function that gossips about changes to CoreData-updating functions
(b) customize the @State variable used by the TextField

The answer below seems long, but it's actually very little code and fairly easy. I just overexplain things, sorry.


The Extension Approach


TextField will still use your vanilla in-memory @State variable. To overhear changes in the binding, add the extension below minus my comments.

ExtBinding.swift
Code Block swift
import Foundation
import Combine
extension Binding {
func didSet(_ then: @escaping (Value) -> Void) -> Binding {
return Binding(
get: { return self.wrappedValue },
set: {
then($0)
self.wrappedValue = $0
}
)
}
}
Line 4 —— Extension means "gives all Bindings the ability to use the new function below"
Line 5 —— This "layers" a new Binding that doesn't disturb reading data, but
does do something special when you write. That something special
Line 9 —— is "then($0)", which escapes the new wrappedValue outside this function,
so you can do something unique inside your View.
Finally — I put this in a separate file, even a separate Extensions folder,
so it's easy to find for someone else or me in six months.

Now, add .didSet { } after the TextField's text binding, as below. A few notes:
  • If you're missing the function parentheses, I left them off. Swift lets us do so for closures at the end of a function.

  • When the binding is updated by typing, anything I write in that closure will be executed.

  • Inside the closure is binding's new value, which you can access by naming it however you'd like

Code Block swift
TextField("Your Label", $textFieldData.didSet { newText in
react(to: newText) } )
Line 2 — That's a function in my View struct. For example, just below var body: some View { ... }
func react(to text: String) {
// Do something with your latest text
}

Finally, if you want the TextField to appear at app launch with text from CoreData, you can:
(a) initialize the @State var with an initial value
(b) add to the TextField().onAppear { myStateVar = getData() }

My preferred practice is to initialize the @State variable, the dependency is thus clear up-front. Doing so is simple, but uses some notation to get at the @State object in different ways. Below is an example, but then a warning.

Code Block swift
struct SomeSubView: View {
@State var text: String
init (initialText: String) {
_text = State(initialValue: initialText)
}
Line 4 —— The parent view supplies the data, either an @ObservableObject or text itself.
Line 5 —— Instead of the self. notation for setting normal variables,
underbar points to the Binding variable. It's a cousin to $.

Let me know if that doesn't work. The custom variable approach is the same concept, except the Binding definition in the Extension becomes the declaration of your @State variable. I prefer the extension approach because then my code is cleaner: my variable takes a single line up top, is initialized clearly with a dependency, and the TextField specifies it is going to call an action.

Warning 1 The code above does not include a debounce mechanism, which means every character typed in will call save in your CoreData database. Yikes! You might find an example, test it, and share it here for others. I decided to use AppKit's text field because it lets me limit the frequency of saves to CoreData, customize the view so it's pretty, and accept rich text editing and pictures. I posted an example implementation today on StackOverflow. If you're writing for iOS, you can find a UIKit version also on StackOverflow. I can walk you through either.

Warning 2 The way you setup CoreData — which follows almost every single tutorial on SwiftUI and CoreData available — violates the MVVM pattern SwiftUI promotes. MVVM is one wise method to create clean code; it requires your View does not directly interact with your Model. The reasoning is this prevents, littered throughout View code, accidental reads or writes to the Model that you wouldn't want, but forgot about with time or that your new team member may not know about until *head*desk* hours later. Also, if you wanted to change the structure of your CoreData model or switch to Google's Firebase to launch your app on Android, you'd have to refactor every view. (Good for Apple?)

The fix: Manage all CoreData fetches and saves in one Class, which your View Model accesses to initialize the in-memory data store. In this way, the Google Firebase remodel above would only require switching one class for another. Further, if you create a Protocol for a DataManager, you can have your ViewModel require only a DataManager, which means that as long as your parsed data structure stays the same, you can simply swap out a CoreData DataManager for a Firebase DataManager without changing perhaps anything in your ViewModel or Views! If you want, I can point you to a tutorial or two.

For hobbyist or quick mock-up purposes, sure @FetchRequest and ignoring separation of concerns is fast and sweet... but it's not SwiftUI-ish because it violates the fundamental pattern, simplicity, and separation of concern that it was meant to promote. Neglecting separation of concerns will just generate frustration when you make a semi-complex app and take breaks between looking at files. OK, soap box over.
Hey @wingover, could you please share the tutorials you’re talking about please? I’m looking for some best practices regarding how to manage Core Data in the MVVM pattern, notably if objects should be wrapped in struct when used in the app.

Is there a native solution for this other than having to implement our own extension for this.... seems like something that should just work out of the box.