Search code examples
swiftarkitrealitykit

Why does RealityKit memory does not clear after deinit called?


I cannot manage to release my RealityKit ARView() from memory. I am aware that there were similar issues with ARKit + SceneKit with workarounds which doesn't solve my problem, unfortunately.

The solutions above kind of work by removing everything "suspicious" manually. That is exactly what I did in an even wider scope:

func closeCurrentView(completion: (() -> Void)? = nil, isScanAnotherFloor: Bool = false) {
    if backgroundRenderingID != UIBackgroundTaskIdentifier.invalid {
        let app = UIApplication.shared
        app.endBackgroundTask(self.backgroundRenderingID)
        self.backgroundRenderingID = UIBackgroundTaskIdentifier.invalid
    }
    self.arView?.session.pause()
    self.arView?.session.delegate = nil
    self.arView?.scene.anchors.removeAll()
    self.arView?.removeFromSuperview()
    self.arView?.window?.resignKey()
    self.arView = nil
}

Memory will rise to 90MB to 250MB and once deinit is called it will reduce to 175MB, not clearing all the memory.

Also at the time of initializing, I set proper options too.

arView?.renderOptions = [
    .disableMotionBlur,
    .disableDepthOfField,
    .disablePersonOcclusion,
    .disableGroundingShadows,
    .disableFaceOcclusions,
    .disableHDR
]

But still no luck.

enter image description here


Solution

  • UIKit view for RealityKit apps

    Alas, RealityKit 4.0 developers can't deallocate ARView from heap memory because there is a poor-quality implementation on Apple's part. Even if you declare arView property as weak in SwiftUI, this instance will be immediately deallocated, so you can't use it. In UIKit, however, declaring arView as weak has no effect.

    As you remember, ARC was firstly introduced in Objective-C and later implemented in Swift. It's quite possible that the weak and unowned functionality is not implemented for ARView for some reason, perhaps because RealityKit is tailored for Swift only – @objc attribute explicitly states this. It looks like ARView weak reference isn't tracked by ARC (or there's no an associated Side Table).

    @available(macOS 10.15, iOS 13.0, *)
    @available(visionOS, unavailable)
    @MainActor @preconcurrency 
    @objc open class ARView : ARViewBase 
    

    If you need more info, please read this post for details.



    SwiftUI view for RealityKit apps

    Unfortunately, with the advent of SwiftUI's RealityView in iOS and visionOS, the situation has not changed: memory leaks still occur. Now the story continues with Value types. Tested on Xcode 16.0.

    @available(visionOS 1.0, macOS 15.0, iOS 18.0, *)
    @MainActor @preconcurrency 
    public struct RealityView<Content> : View where Content : View