What is "reference may have escaped from deinit"?

Hi i'm trying to serialize some work on queues and i'm getting a crash with this error. I'm not sure what it means, and i'm not sure where the crash site actually is.
Can someone help me understand what this is? thanks!

2023-05-07 12:40:35.4180 - 10752148672 - AppleCameraDataDelegate: DEINIT
Object 0x104f2f3a0 deallocated with retain count 2, reference may have escaped from deinit.
2023-05-07 12:40:35.418718-0400 booth[29128:2090318] Object 0x104f2f3a0 deallocated with retain count 2, reference may have escaped from deinit.

This error was added in this PR, which provides a bit more explanation. The issue is that in deinit we want to be able to call methods on self, but it's also possible for methods on self to form new strong references to self which outlive the duration of the deinit. This is what's being referred to as a reference having 'escaped.'

Such an escape is illegal because once deinit finishes the memory for the class instance is deallocated, and prior to the linked PR it would be possible for that memory to be accessed through the persisting strong reference, which is a memory safety issue. The current behavior will double check that before we deallocate a class instance, no additional references to the object we are deallocating still exist. Since deinit will only be called when the last reference to an object is released, in such a circumstance we know that something in the deinit has caused self to escape.

As for where the crash is happening, I can't be sure but it looks like it's happening as a result of the AppleCameraDataDelegate deinit. I would take a look at what you're doing in that deinit to see where a reference could be kept alive after deinit returns.


Thank you so much for the quick & detailed response! I never would have figured that out. With that info it was easy to find what was going on: deinit was calling into an async dispatch that referenced self. D'oh. Fixed!

1 Like