Post

Replies

Boosts

Views

Activity

SwiftData doesn't parse my object correctly
Hello, im trying to parse a JSON Request into a Swift Data Model. The specific bug happens with the nutriscore. It works perfectly fine if I do my request and Decode or Encode the Model directly. But when im trying to add it to the Database the field is empty. Somehow when im iterating through each product (my model) and console log it, it works. But only if there is one product in my database. sometimes when im adding another product, it somehow deletes(?) all nutriscores and the console log prints "nil" for all products. even for the product it worked before. This right here is the way I insert into my database which should be perfectly fine. And the printing works also perfectly fine and it always displays the correct nutriscore func dataScanner(_ dataScanner: DataScannerViewController, didAdd addedItems: [RecognizedItem], allItems: [RecognizedItem]) { for item in addedItems { if case let .barcode(barcode) = item { performAPIRequest(with: barcode.payloadStringValue!) { result in switch result { case .success(let product): ... var descriptor: FetchDescriptor<Product> { var descriptor = FetchDescriptor<Product>( predicate: #Predicate { $0.code == product.code } ) descriptor.fetchLimit = 1 return descriptor } var products: [Product] = [] products = try! self.parent.context.fetch(descriptor) print(product.nutriscore ?? "no nutri"); //WORKS PERFECTLY FINE!! if let existingProduct = products.first { existingProduct.amount! += 1 existingProduct.lastScannedAt = Date() } else { self.parent.context.insert(product) } self.processMeals() case .failure(let error): print("Error: \(error)") } } } } } This has to be a SwiftData Bug, or why doesn't it work
1
0
481
May ’24