Last active
July 22, 2025 09:20
-
-
Save iandundas/a2a4b8082f645f67d160e96df5ca4de6 to your computer and use it in GitHub Desktop.
Eventually a EXC_BAD_ACCESS
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
/* | |
Eventually throws a EXC_BAD_ACCESS, reliably around iteration 130688, I think due to stack overflow. | |
https://share.cleanshot.com/qQdj9ygc | |
*/ | |
import SwiftUI | |
@Observable | |
class MyObservableCounter { | |
var value = 0 | |
func start() { | |
value += 1 | |
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) { | |
self.start() | |
} | |
} | |
} | |
class Owner { | |
let counter = MyObservableCounter() | |
func setup() { | |
withObservationTracking(of: self.counter.value) { value in | |
print("Counter changed to \(value)") | |
} | |
counter.start() | |
} | |
} | |
struct ContentView: View { | |
@State var owner = Owner() | |
var body: some View { | |
VStack { | |
Text("Hello") | |
} | |
.onAppear { | |
owner.setup() | |
} | |
} | |
} | |
// https://www.polpiella.dev/observable-outside-of-a-view | |
public func withObservationTracking<T>(of value: @escaping @autoclosure () -> T, execute: @escaping (T) -> Void) { | |
Observation.withObservationTracking { | |
execute(value()) | |
} onChange: { | |
RunLoop.current.perform { | |
withObservationTracking(of: value(), execute: execute) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment