Last active
September 16, 2023 11:34
-
-
Save helje5/7ebe7cd87ba410958d96448635b43f22 to your computer and use it in GitHub Desktop.
Repeated Model Inits w/ State
This file contains hidden or 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
import SwiftUI | |
@Observable class Tester { | |
init() { print("INIT:", ObjectIdentifier(self)) } | |
deinit { print("DEINIT:", ObjectIdentifier(self)) } | |
} | |
struct ContentView: View { | |
struct Nested: View { | |
@State var other = 42 | |
@State var tester = Tester() | |
let refresher : Int | |
init(refresher: Int) { | |
self.refresher = refresher | |
print("Nested-init:", refresher, ObjectIdentifier(tester)) | |
} | |
var body: some View { | |
print("Bested body:", refresher, ObjectIdentifier(tester)) | |
return VStack { | |
Text("Other: \(other)") | |
Text(verbatim: "Tester: \(ObjectIdentifier(tester))") | |
Text("Refresh: \(refresher)") | |
Button("Bump Other") { other += 1 } | |
} | |
} | |
} | |
@State private var refresher = 0 | |
var body: some View { | |
VStack { | |
Nested(refresher: refresher) | |
Divider() | |
Button("Refresh View") { refresher += 1 } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample run:
Startup, ee40 object is created:
First click: New object gets created (c120), but the body properly sees ee40. Note that the c120 is not deallocated?
Second click: New object gets created (d160), body still ee40, the c120 now gets deallocated.
Third click...