Understanding Core Data — detecting managed objects retain cycle
Apple’s Core Data Programming Guide warns you about strong references between managed objects.
with relationships between managed objects, each object maintains a strong reference to the object or objects to which it is related. This relationship can cause strong reference cycles that in turn can cause objects to be held in memory long past their usefulness
This is not super ideal. All the effort we put to avoid memory leaks, to refer object with weak or unowned reference, renders partially useless. As long as we use Core Data, the framework creates retain cycles for us.
(I am not exactly sure why Core Data is designed this way. Object graph maintenance? Certain relationship transversal optimization? Feel free to leave me some clues in the comment session)
This strong reference-ing behavior is a bit hidden. You can find the elaboration below.
Sample code for the case below can be downloaded here.
Profiling in Instruments
When it comes to investigating retain cycles, my go-to tool is Instruments. Profile my app with Leak template to find memory leaks.
The profile result is not very helpful. It contradicts what the documentation said. If there’s strong reference cycle, shouldn’t it show in the profile result?

I speculate this is related to how “leaks” is detected by Instruments. The way that managed objects are actually referenced to each other probably don’t fall into the “leak bucket” from Instruments perspective.

If we look deeper by searching for the class name of my managed objects, I do see a large number of them unexpectedly show up.
Clearly, the situation described in documentation exists — managed objects do persist in memory long after their usefulness!
What about Xcode memory debugger?
The situation in Xcode memory debugger is the same. No retain cycle from runtime issue inspector. But objects do persist in memory when I search by class name.

To sum up…
Strong reference cycles do happen just as described in documentation. It is not captured in memory debug tool in Xcode nor in Instruments.
In upcoming posts, we will dive deeper to see how to tame this kind of memory leak.
P.S. If you want to see try out the code yourself as well, you can get the sample code here.