简体   繁体   中英

SwiftUI TextField Causing Memory Leaks

I've been tracking down a memory leak problem in my project for a number of days now and have seemed to isolated it to views using a TextField. When using a TextField in a view, navigating away and then back to the view causes a memory leak to show up in Instruments.

The project contains multiple navigation links and is working with core data, but I was able to reproduce the problem using a minimal project with two navigation links and no core data. The links navigate to a simple view containing a Text item and a TextField both referring to a single @State variable. Navigating between the two views without entering any data into the TextField is sufficient to trigger the leak in Instruments. Commenting out the TextField with no other changes prevents the leak from showing up.

The minimal project was created for Multiplatform with the leak found using macOS for the target (didn't try any iOS targets as not working them right now). Xcode version is 13.2.1. Deployment target is macOS 12.0. Running on a MacBook Pro with Monterey version 12.2 Beta.

Here's the code for the Content view:

struct ContentView: View {
    
    var body: some View {
        NavigationView {
            List {
                NavigationLink("Link 1", destination: TestView())
                NavigationLink("Link 2", destination: TestView())
            }
        }
        
    }
}

And for the TestView:

struct TestView: View {
    @State var testString = "Hello, world!"
    var body: some View {
        VStack {
            Text(testString)
            TextField("Test", text: $testString)
        }
        .padding()
    }
}

When just running under Xcode I also noted occasionally the debug area showing the message "onChange(of: Bool) action tried to update multiple times per frame." No idea why that's happening either, though it seems independent of whether the TextField is present or not.

If anyone could tell me what/why this is happening and if I should worry about these leaks or not I would greatly appreciate it.

Added 12/30/21: I tried replacing the TextField with TextEdit and the memory leak no longer showed up when shifting between views.

Also 12/30/21: reference should have been to using TextEditor, not TextEdit.

I'm seeing this issue when using an apple pencil and the TextField with an.onSubmit modifier. If I use an on screen keyboard there is no leak.

I found that when I added.keyboardType(.numberPad) to the TextField the issue was resolved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM