5

Why is the order of my array random when i use the @Model macro.

class TestModel {
var name: String?
var array: \[TestModel2\]

    init(name: String = "") {
        self.name = name
        array = []
    }

}

class TestModel2 {
var name: String?

    init(name: String = "") {
        self.name = name
    }

}

This works fine, and all the items in array are in the order I add them.

But if I declare both of them as @Model, like this:


@Model
class TestModel {
var name: String?
var array: \[TestModel2\]

    init(name: String = "") {
        self.name = name
        array = []
    }

}

@Model
class TestModel2 {
var name: String?

    init(name: String = "") {
        self.name = name
    }

}

The array items are always in a random order. When I reload the view where they are displayed or when I add items to the array the order is randomised.

This behaviour can also be seen in the sample code here. When adding bucket list items to a trip, the items are always displayed in a random order.

Is this a beta bug? Or is this intended?

  • Not sure what you have defined in your model, usually one uses `@Relationship` when two models are connected. – Joakim Danielson Aug 12 '23 at 16:08
  • According to the docs `@Relationship` is only required to specify a custom deletion rule. "When a model contains an attribute whose type is also a model (or a collection of models), SwiftData implicitly manages the relationship between those models for you. By default, the framework sets relationship attributes to nil after you delete a related model instance. To specify a different deletion rule, annotate the property with the Relationship(_:_:originalName:inverse:hashModifier:) macro. " When I add @Relationship`to the model, there is no difference to the outcome. – Florian Liegl Aug 12 '23 at 16:46
  • 1
    I must have missed that part, excellent since it will simplify things. SwiftData uses Core Data under the hood and Core Data uses `Set` for to-many relationships properties so that is most likely why your array property changes order all the time. – Joakim Danielson Aug 12 '23 at 18:49
  • I also had the same issue so I used a time stamp and sort the data based on them when fetching it. – user11640506 Aug 14 '23 at 08:59
  • 1
    @user11640506 How do you sort `TestModel2` if you have a query on `TestModel`? – Joakim Danielson Aug 14 '23 at 09:40
  • @user11640506 that seems to be the only solution, but it does not make sense as it is easy to make a mistake as sort order changes after adding new data. – Mikrasya Aug 25 '23 at 06:37

0 Answers0