swiftswiftuimemory-leaksheap-memorydynamic-memory-allocation

Heap Memory Stair-Case rising in SwiftUI project


A simple keyboard extension app showing continuous heap memory allocation each time open the keyboard on screen.

For easier understanding see the image below...

https://github.com/Asim99x/KeyboardTest/blob/main/ScreenShot.gif

Here is the KeyboardViewController:

class KeyboardViewController: UIInputViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
                
        let myController = UIHostingController(
            rootView: AnimalKeyboardView(
                insertText: { [weak self] text in
                    guard let self else { return }
                    self.textDocumentProxy.insertText(text)
                }
            ))
        
        let animalKeyboardView = myController.view!
        animalKeyboardView.translatesAutoresizingMaskIntoConstraints = false

        self.addChild(myController)
        self.view.addSubview(animalKeyboardView)
        myController.didMove(toParent: self)

        NSLayoutConstraint.activate([
            animalKeyboardView.leftAnchor.constraint(equalTo: view.leftAnchor),
            animalKeyboardView.topAnchor.constraint(equalTo: view.topAnchor),
            animalKeyboardView.rightAnchor.constraint(equalTo: view.rightAnchor),
            animalKeyboardView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
    }
}

And AnimalKeyboardView:

struct AnimalKeyboardView: View {
    
    var insertText: (String) -> Void

    private let animalList = ["🐱", "🐷", "đŸĻĢ", "đŸĻ­", "đŸŧ", "🐮", "🐰", "🐭", "🐘", "🐹", "đŸĻŠ", "đŸŦ"]
    private let column = GridItem.init(.adaptive(minimum: 56, maximum: 56), spacing: 32)

    var body: some View {
        VStack(spacing: 24) {
                LazyVGrid(columns: [column], spacing: 24, content: {
                    ForEach(animalList, id: \.self) { animal in
                        Button(action: {
                            insertText(animal)
                        }, label: {
                            Text(animal)
                                .font(.system(size: 32))
                                .padding(.all, 8)
                                .background( RoundedRectangle(cornerRadius: 8)
                                    .fill(.white.opacity(0.8))
                                )
                        })
                    }
                })
            }
            .padding(.top, 32)
            .padding(.bottom, 16)
            .frame(height: 300)
            .frame(maxWidth: .infinity)
    }
}

You can checkout the Github repo here:

https://github.com/Asim99x/KeyboardTest


Solution

  • Looks like the memory leak is coming from Apple. If you remove the SwiftUI view it will still keep leaking memory. I found this old post that might confirm the leak comes from Apple. Keyboard Extension Memory Leak?