Reputation: 19
I have been researching this for days now but I can't find the answer....
I'm loading a single JSON file and decoding into 3 SwiftData classes The loading and decoding works fine and the views of the app show the parent and children classes. However, when I close the app, the relationships are lost. I can see the children data in the sql database but they've lost the relationship to the parent so don't show up in the app as I traverse from the parent view to the children view(s).
The debugPrint (below) shows the child (method) of the parent (recipe) but it doesn't save it in SwiftData. Any ideas?
func loadData (data: AnyPublisher<[Recipe], any Error>) {
data
.sink(
receiveCompletion: { completion in
switch completion {
case .failure(let error):
self.logger.error("Error: \(error.localizedDescription)")
case .finished: break
}
},
receiveValue: { (recipes: [Recipe] ) in
for recipe in recipes {
//insert the new recipe with the methods and ingredients
self.context.insert(recipe)
for method in recipe.method! {
debugPrint(method.step)
}
}
try? self.context.save()
self.logger.notice("Successfully completed JSON decoding for Recipe:")
})
.cancel()
}
Extract of Classes:
@Model
final class Recipe: Codable {
enum CodingKeys: CodingKey {
case name, source, ingredients, method
}
var name: String
var source: String
@Relationship(deleteRule: .cascade, inverse: \Ingredient.recipe)
var ingredients: [Ingredient]? = []
@Relationship(deleteRule: .cascade, inverse: \Method.recipe)
var method: [Method]? = []
@Model
final class Method: Codable {
enum CodingKeys: CodingKey {
case order, step, stepComplete
}
var order: Int
var step: String
var stepComplete: Bool = false
//@Relationship(inverse: \Recipe.ingredients)
var recipe: Recipe?
Upvotes: 1
Views: 852
Reputation: 19
For the benefit of others, I found a solution...
I enabled CloudKit (in anticipation of working cross device) and so had to meet the requirements of optional or default values for properties.
The process of enabling CloudKit has managed to fix the issue so now the relationships persist! This works even if not signed into iCloud on the simulator and works on a real device
Upvotes: 0