iosrealmswiftuixcode11.4

SwiftUI "un-bind" a string from a textfield


I’m trying to store a string from a textfield into a Realm DB. Somehow it doesn't save just the actual string, instead it saves some kind of metatext from the binding:

📄 Binding(transaction: SwiftUI.Transaction(plist: []), location: SwiftUI.StoredLocation, _value: "John Doe")

How can I just save the entered string to realm without the infos surrounding it?

This is my code:

@State var enteredName: String = "" let realm = try! Realm()

for the textfield:

TextField("enter your name", text: $enteredName)
   .textFieldStyle(RoundedBorderTextFieldStyle())

and for the button:

Button(action: {

    let newPerson = Contacts()
    newPerson.name = "\(self.$enteredName)"

    do {
        try self.realm.write {
            self.realm.add(newPerson)
        }
    } catch {
        print("Error saving newPerson \(error)")
    } 
}) {
    Text("Save New Person")   
}

Solution

  • In the Button closure, action, by using the $ symbol you are sending a binding reference to enteredName. You simply need a normal reference, which you can do by removing the $ symbol.

    Your code should be:

    Button(action: {
    
        let newPerson = Contacts()
        newPerson.name = self.enteredName
    
        do {
            try self.realm.write {
                self.realm.add(newPerson)
            }
        } catch {
            print("Error saving newPerson \(error)")
        } 
    }) {
        Text("Save New Person")   
    }