Browse Questions
- The most common causes of memory leaks in iOS are strong reference cycles between classes, closure capture retention, un-invalidated Timers, retained Combine subscriptions, and unmanaged Core…
- Both inject values from the environment, but they serve different purposes.
- Both safely unwrap optionals, but they differ in scope and intent.
- Instruments diagnoses memory issues through the Leaks instrument for automated heap scans and the Allocations instrument with Mark Generation for tracking persistent abandoned memory.
Answer: Both inject values from the environment, but they serve different purposes.
@Environment— reads system or built-in values (color scheme, locale, font, dismiss action)@EnvironmentObject— reads a customObservableObjectinjected by a parent view
Code Example:
// @Environment — built-in system values
struct ThemeAwareView: View {
@Environment(\.colorScheme) var colorScheme
@Environment(\.dismiss) var dismiss
var body: some View {
Text(colorScheme == .dark ? "Dark mode" : "Light mode")
Button("Close") { dismiss() }
}
}
// @EnvironmentObject — custom shared object
class AppSettings: ObservableObject {
@Published var fontSize: CGFloat = 16
}
struct ChildView: View {
@EnvironmentObject var settings: AppSettings
var body: some View {
Text("Hello").font(.system(size: settings.fontSize))
}
}
// Must be injected by a parent
ContentView()
.environmentObject(AppSettings())