Posts

Post not yet marked as solved
3 Replies
3.9k Views
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") } } } }
Posted
by mwd1973.
Last updated
.