After copying and inserting instances I am getting strange duplicate values in arrays before saving.
My models:
@Model
class Car: Identifiable {
@Attribute(.unique)
var name: String
var carData: CarData
func copy() -> Car {
Car(
name: "temporaryNewName",
carData: carData
)
}
}
@Model
class CarData: Identifiable {
var id: UUID = UUID()
var featuresA: [Feature]
var featuresB: [Feature]
func copy() -> CarData {
CarData(
id: UUID(),
featuresA: featuresA,
featuresB: featuresB
)
}
}
@Model
class Feature: Identifiable {
@Attribute(.unique)
var id: Int
@Attribute(.unique)
var name: String
@Relationship(
deleteRule:.cascade,
inverse: \CarData.featuresA
)
private(set) var carDatasA: [CarData]?
@Relationship(
deleteRule:.cascade,
inverse: \CarData.featuresB
)
private(set) var carDatasB: [CarData]?
}
The Car instances are created and saved to SwiftData, after that in code:
var fetchDescriptor = FetchDescriptor<Car>(
predicate: #Predicate<Car> {
car in
car.name == name
}
)
let cars = try! modelContext.fetch(
fetchDescriptor
)
let car = cars.first!
print("car featuresA:", car.featuresA.map{$0.name}) //prints ["green"] - expected
let newCar = car.copy()
newCar.name = "Another car"
newcar.carData = car.carData.copy()
print("newCar featuresA:", newCar.featuresA.map{$0.name}) //prints ["green"] - expected
modelContext.insert(newCar)
print("newCar featuresA:", newCar.featuresA.map{$0.name}) //prints ["green", "green"] - UNEXPECTED!
/*some code planned here modifying newCar.featuresA, but they are wrong here causing issues,
for example finding first expected green value and removing it will still keep the unexpected duplicate
(unless iterating over all arrays to delete all unexpected duplicates - not optimal and sloooooow).*/
try! modelContext.save()
print("newCar featuresA:", newCar.featuresA.map{$0.name}) //prints ["green"] - self-auto-healed???
Tested on iOS 18.2 simulator and iOS 18.3.1 device. Minimum deployment target: iOS 17.4
The business logic is that new instances need to be created by copying and modifying previously created ones, but I would like to avoid saving before all instances are created, because saving after creating each instance separately takes too much time overall. (In real life scenario there are more than 10K objects with much more properties, updating just ~10 instances with saving takes around 1 minute on iPhone 16 Pro.)
Is this a bug, or how can I modify the code (without workarounds like deleting duplicate values) to not get duplicate values between insert() and save()?