Skip to content

Instantly share code, notes, and snippets.

@helje5
Last active September 16, 2023 11:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save helje5/7ebe7cd87ba410958d96448635b43f22 to your computer and use it in GitHub Desktop.
Save helje5/7ebe7cd87ba410958d96448635b43f22 to your computer and use it in GitHub Desktop.
Repeated Model Inits w/ State
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 }
}
}
}
@helje5
Copy link
Author

helje5 commented Sep 16, 2023

Sample run:

Startup, ee40 object is created:

INIT: ObjectIdentifier(0x000060000023ee40)
Nested-init: 0 ObjectIdentifier(0x000060000023ee40)
Nested body: 0 ObjectIdentifier(0x000060000023ee40)

First click: New object gets created (c120), but the body properly sees ee40. Note that the c120 is not deallocated?

INIT: ObjectIdentifier(0x000060000027c120)
Nested-init: 1 ObjectIdentifier(0x000060000027c120)
Nested body: 1 ObjectIdentifier(0x000060000023ee40)

Second click: New object gets created (d160), body still ee40, the c120 now gets deallocated.

INIT: ObjectIdentifier(0x000060000027d160)
Nested-init: 2 ObjectIdentifier(0x000060000027d160)
DEINIT: ObjectIdentifier(0x000060000027c120)
Nested body: 2 ObjectIdentifier(0x000060000023ee40)

Third click...

INIT: ObjectIdentifier(0x0000600000278980)
Nested-init: 3 ObjectIdentifier(0x0000600000278980)
DEINIT: ObjectIdentifier(0x000060000027d160)
Nested body: 3 ObjectIdentifier(0x000060000023ee40)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment