Created
March 30, 2022 05:12
-
-
Save frank89722/9b529203b4ddd4a87377b0e0a6ac249f to your computer and use it in GitHub Desktop.
swiftui_memory_leak_issue_demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// ContentView.swift | |
// Shared | |
// | |
// Created by Frank V on 2022/3/30. | |
// | |
import SwiftUI | |
class TestViewModel_A: ObservableObject { | |
func refresh() async { | |
//Do some refresh thing | |
try? await Task.sleep(nanoseconds: 200_000_000) | |
} | |
} | |
class TestViewModel_B: TestViewModel_A {} | |
class TestViewModel_C: TestViewModel_A {} | |
struct ContentView: View { | |
@StateObject var viewModel = TestViewModel_A() | |
var body: some View { | |
NavigationView { | |
List { | |
NavigationLink("NextView") { | |
NextView() | |
} | |
} | |
.navigationTitle("Test Title") | |
.navigationBarTitleDisplayMode(.automatic) | |
} | |
} | |
} | |
/* | |
This view is using `.navigationBarTitleDisplayMode(.automatic)` and | |
call a function in it's view model from `.refreshable()`. | |
The `viewModel` will never deinit | |
*/ | |
struct NextView: View { | |
@StateObject var viewModel = TestViewModel_B() | |
var body: some View { | |
List { | |
NavigationLink("AnotherView") { | |
AnotherView() | |
} | |
} | |
.navigationTitle("Next Title") | |
.navigationBarTitleDisplayMode(.automatic) | |
.refreshable { | |
await viewModel.refresh() | |
} | |
} | |
} | |
/* | |
This view using `.navigationBarTitleDisplayMode(.inline)` and have no | |
issue with `.refreshable()` | |
*/ | |
struct AnotherView: View { | |
@StateObject var viewModel = TestViewModel_C() | |
var body: some View { | |
List { | |
VStack { | |
Text("Last view") | |
} | |
} | |
.navigationTitle("Another Title") | |
.navigationBarTitleDisplayMode(.inline) | |
.refreshable { | |
await viewModel.refresh() | |
} | |
} | |
} | |
struct ContentView_Previews: PreviewProvider { | |
static var previews: some View { | |
ContentView() | |
NextView() | |
AnotherView() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment