Does @Relationship(inverse:) create a memory leak?

Hi, I am creating (or trying to) my first app using SwiftData - and I have questions :-)

The main question I can't get my head wrapped around is the following:

Let's say I have the sample below...

@Model
class Person {
@Relationship(inverse:\Hat.owner) var hat:Hat
}
@Model
class Hat {
var owner:Person?
}

It looks like I am creating a strong reference cycle between the person and the hat objects? And in fact I am seeing these kinds of reference cycles when I look at the memory debugger.

Many code samples I have seen so far use this type of relationship declaration...

And I am wondering: Am I missing something? Admittedly I don't find many discussions about memory leaks caused by SwiftData despite the syntax being used in many examples?

So what is the situation? Did Apple just miss to explain that the inverse: declaration causes memory leaks or is there some kind of magic that I should understand?

Answered by DTS Engineer in 831706022

No, there is no reference cycle and memory leak here. By using @Model, hat and owner are converted to computed properties, and some logics are implemented there to maintain the integrity of the relationship. Those details are barely documented, but conceptually, SwiftData takes care the integrity and so you don't need to worry about that.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Accepted Answer

No, there is no reference cycle and memory leak here. By using @Model, hat and owner are converted to computed properties, and some logics are implemented there to maintain the integrity of the relationship. Those details are barely documented, but conceptually, SwiftData takes care the integrity and so you don't need to worry about that.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Hmmm.... Wild! I was playing around with my app and stopping now and then and checking for leaks in the Debug Memory Graph. In there some of my objects stayed around much longer than their lifespan and where even flagged as leaked. Looking at the graphs I did see pretty impressive node cycles. Howevery when I continue using the app, these objects seem to disappear and even the 'leaked' objects are gone. Which means the memory graph itself is probably useless? How am I supposed to check if I am having memory leaks or not? I am dealing with pretty large images, so I really need to be sure... Do I need to create a new modelContext to be sure that I get rid of objects I do not need any more?

Does @Relationship(inverse:) create a memory leak?
 
 
Q