Rules Hub
Coding Rules Library
← Back to all rules
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
mobile ruleP1stack specificStack: SwiftUI
swiftuistatelifecycle
Own observable objects with @StateObject, inject them with @ObservedObject
Use `@StateObject` in the view that creates and owns an observable object's lifecycle; use `@ObservedObject` (or `@EnvironmentObject`) in views that receive one created elsewhere. Re-declaring an injected object as `@StateObject` gives it a second, view-local lifecycle and detaches it from the real source of truth.
PR: profico-org-corpus batch2 (all stacks/products)Created: Jul 26, 2026
Bad example
Old codeswift
| 1 | struct ChildView: View { |
| 2 | @StateObject var settings: AppSettings // passed in from parent |
| 3 | } |
Explanation (EN)
The child re-owns an object it was given, creating a duplicate lifecycle.
Objašnjenje (HR)
Good example
New codeswift
| 1 | struct ChildView: View { |
| 2 | @ObservedObject var settings: AppSettings // owned by the parent |
| 3 | } |
Explanation (EN)
The child observes the injected object without taking ownership.
Objašnjenje (HR)