Inexperienced "senior" coder here. Learning by imitation, but going relatively well. Keep rebuilding my App and it gets better with each iteration but I then get to the same stumbling block each time... the Product Category and the associated Picker that I am trying to implement.
In my latest iteration, I keep getting the following error in the Xcode Console when running my App in the simulator and going to the associated view:
Picker: the selection "nil" is invalid and does not have an associated tag, this will give undefined results.
I am trying to get a simple Category selection applied to a Product. The Category list is a Model/Array on its own.
@Model
class Category {
var name: String = ""
var products: [Product]?
init(
name: String
) {
self.name = name
self.products = []
}
}
@Model
class Product {
var name: String = ""
@Relationship(inverse: \Order.products)
var orders: [Order]?
// @Relationship(inverse: \Category.products)
var category: Category?
init(
name: String,
category: Category? = nil
) {
self.name = name
self.orders = []
self.category = category
}
}
I cannot select an item in the picker and it is not persisted in the Product record.
struct AddProductView: View {
@Environment(\.dismiss) private var dismiss
@Environment(\.modelContext) var context
@Environment(\.presentationMode) var presentationMode
@Query(sort: \Category.name) var categories: [Category]
@State private var name: String = ""
@State private var category: Category?
var body: some View {
NavigationStack {
Form {
TextField("New Product Name", text: $name)
VStack {
Section {
Picker("Choose a Category?", selection: $category) {
// Text("").tag("")
ForEach(categories, id:\.self) { category in
Text(category.name).tag(category.name)
}
}
}
}
}
.navigationTitle("New Product")
.navigationBarTitleDisplayMode(.large)
.toolbar {
ToolbarItem(placement: .topBarLeading) {
Button("Cancel") { dismiss() }
}
// MARK: Need to add data check on name field
ToolbarItem(placement: .topBarTrailing) {
Button("Save") {
let product = Product(name: name)
context.insert(product)
dismiss()
}
}
}
}
}
}
I must be doing something simple incorrectly, but I cannot see it.
My App is using SwiftData for persistence and is linked to iCloud.
Any thoughts, suggestions, or guidance, would be much appreciated.
Simon