Why I Stopped Using @ObservedObject — The @Observable Macro Explained
The developer encountered problems with SwiftUI's property wrappers, specifically `@ObservedObject`, `@StateObject`, and `@EnvironmentObject`. They experienced issues like phantom re-renders, crashes due to missing environment objects, and retain cycles. For instance, using `@ObservedObject` directly in a view caused the view model to reset and lose state on every parent view re-render. The introduction of the `@Observable` macro, available since iOS 17, resolved these issues by allowing model classes to be observable without needing Combine's `@Published` ceremony or multiple property wrappers.
The adoption of `@Observable` reflects a broader trend in Apple's ecosystem towards simplifying developer workflows and reducing error-prone code. By streamlining state management, Apple aims to make it easier for developers to focus on building features rather than debugging. This move also aligns with the company's efforts to enhance the overall developer experience, as seen in initiatives like SwiftUI and Combine. The `@Observable` macro's impact is significant, as it eliminates the need for developers to memorize and choose between multiple property wrappers, reducing the likelihood of mistakes.
The implications of this shift are substantial, particularly for developers supporting older iOS versions. Since `@Observable` requires iOS 17 or macOS 14, developers must weigh the benefits of adopting this new approach against the need to support legacy platforms. As the developer community continues to explore and adopt `@Observable`, it will be essential to monitor the prevalence of errors and crashes in SwiftUI applications and assess the overall impact on app development workflows. Additionally, developers should be aware of the potential gotchas, such as the need for `@Bindable` when implementing two-way binding.
Key Takeaways
The `@Observable` macro simplifies state management in SwiftUI by eliminating the need for multiple property wrappers.
Adopting `@Observable` requires iOS 17 or macOS 14, posing a challenge for developers supporting older platforms.
The `@Observable` macro reduces errors like phantom re-renders and crashes due to missing environment objects.
Developers must consider the trade-offs between adopting new features and supporting legacy platforms.
About the Source
This analysis is based on reporting by Medium. Here is a short excerpt for context:
It’s 11pm again. But this time, I’m not Googling which property wrapper to use — I deleted the problem instead. Continue reading on Medium »Read the original at Medium