Skip to content

Instantly share code, notes, and snippets.

@Tunous
Last active September 3, 2023 09:35
Show Gist options
  • Save Tunous/4d7c56fb13813bf1912a99aaae062cc2 to your computer and use it in GitHub Desktop.
Save Tunous/4d7c56fb13813bf1912a99aaae062cc2 to your computer and use it in GitHub Desktop.
StateObject memory leak
import SwiftUI
struct ContentView: View {
@State private var showSheet1 = false
@State private var showSheet2 = false
@State private var showSheet3 = false
var body: some View {
VStack {
Button("State object created directly") {
showSheet1 = true
}
.sheet(isPresented: $showSheet1) {
StateObjectCreatedDirectly()
}
Button("State object created inline") {
showSheet2 = true
}
.sheet(isPresented: $showSheet2) {
StateObjectCreatedInline()
}
Button("State object created created before") {
showSheet3 = true
}
.sheet(isPresented: $showSheet3) {
StateObjectCreatedBefore()
}
}
}
}
struct StateObjectCreatedDirectly: View {
@StateObject private var myClass = MyClass()
var body: some View {
Text("Sheet")
}
}
struct StateObjectCreatedInline: View {
@StateObject private var myClass: MyClass
init() {
self._myClass = StateObject(wrappedValue: MyClass())
}
var body: some View {
Text("Sheet")
}
}
struct StateObjectCreatedBefore: View {
@StateObject private var myClass: MyClass
init() {
let myClass = MyClass()
self._myClass = StateObject(wrappedValue: myClass)
}
var body: some View {
Text("Sheet")
}
}
final class MyClass: ObservableObject {
init() {
print("Initializing \(ObjectIdentifier(self))")
}
deinit {
print("Deinitializing \(ObjectIdentifier(self))")
}
}
#Preview {
ContentView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment