I am new to SwiftUI and realm. I have created a Customer class as written below. I am trying to add some information to Realm database. My code is like this. And when I am trying to run it, I am getting error: "Cannot add an object with observers to a Realm."
Realm version is 10.28.6 SwiftUI 5 Xcode 13.4
import SwiftUI
import RealmSwift
class Customer: Object, ObjectKeyIdentifiable {
@Persisted(primaryKey: true) var accountNumber = ""
@Persisted var customerName = ""
@Persisted var phoneNumber = ""
@Persisted var address = ""
@Persisted var city = ""
@Persisted var state = ""
@Persisted var zip = ""
}
//
// ContentView.swift
// ProjTests
//
// Realm 10.28.6
import SwiftUI
import RealmSwift
struct ContentView: View {
@Environment(\.realm) var realm
@Environment(\.dismiss) var dismiss
@ObservedRealmObject var customer = Customer()
// @ObservedRealmObject var customer: Customer
var body: some View {
NavigationView {
Form {
Section {
VStack(alignment: .leading) {
Text("Customer Name")
TextField("Name", text: $customer.customerName)
.disableAutocorrection(true)
.textFieldStyle(RoundedBorderTextFieldStyle())
}
}
Section {
VStack(alignment: .leading){
Text("Phone Number")
TextField("10-digit Phone Number", text: $customer.phoneNumber)
.textFieldStyle(RoundedBorderTextFieldStyle())
}
}
Section {
VStack(alignment: .leading) {
Text("Address")
TextField("Address", text: $customer.address)
TextField("City", text: $customer.city)
TextField("State", text: $customer.state)
TextField("PIN Code", text: $customer.zip)
}
}
Section {
DatePicker("Date", selection: $customer.loanDate, displayedComponents: .date)
}
HStack() {
Button("Submit") {
customer.accountNumber = generateAccountNumber()
try? realm.write {
realm.add(customer)
}
}
}
.frame(width: 300, height: 15, alignment: .center)
}
.navigationTitle("Add New Customer")
}
}
}
extension ContentView {
func generateAccountNumber() -> String {
let newAccountNumber = Int.random(in: 10000000..<99999999)
return(String(newAccountNumber))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I will be very thankful for your help.