# @StateObject

[SwiftUI](/ios/swiftui.md) ⟩ [view](/ios/swiftui/view.md) ⟩ [state](/ios/swiftui/view/state.md) ⟩ [object](/ios/swiftui/view/state/object.md) ⟩ @StateObject

{% hint style="success" %}
Use <mark style="color:purple;">`@StateObject`</mark> to <mark style="color:yellow;">declare</mark> and <mark style="color:yellow;">initialize</mark> a [state object](/ios/swiftui/view/state/object.md) in a [view](/ios/swiftui/view.md) that [observes](/ios/swiftui/view/state/observable-object/observer.md) the object's [data](/ios/master/term/data-model.md).
{% endhint %}

```swift
// ⭐️ 1. declare a type that conforms to `ObservableObject`
class Zoo : ObservableObject {

    // ⭐️ 2. declare published value(s) in this type
    @Published var creatures = [
        Creature(name: "Gorilla", emoji: "🦍"),
        Creature(name: "Peacock", emoji: "🦚"),
    ]
    
}

// content view
struct ContentView: View {

    // ⭐️ 3. declare & initialize a state object
    @StateObject var data = Zoo()
    
    var body: some View {
        // 4. access the state object's data in subviews
    }
}
```

{% tabs %}
{% tab title="💈範例" %}
📗 參考：Swift Playgrounds (Keep Going with Apps) - Sharing Data Between Views.

📁 CreatureZoo&#x20;

```swift
// ⭐️ 1. declare an observable object type
class CreatureZoo : ObservableObject {
    // ⭐️ 2. declare published properties
    @Published var creatures = [
        Creature(name: "Gorilla", emoji: "🦍"),
        Creature(name: "Peacock", emoji: "🦚"),
    ]
}
```

📁 MyApp

```swift
@main
struct MyApp: App {
    
    // ⭐️ 3. intialize an observable object
    @StateObject var data = CreatureZoo()
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                // ⭐️ 4. put data in environment
                .environmentObject(data)
        }
    }
}
```

📁 ContentView

```swift
struct ContentView: View {
    
    // ⭐️ 5. inject data from environment
    @EnvironmentObject var data : CreatureZoo

    var body: some View {
        // ⭐️ 6. access data in subviews
    }
}
```

{% endtab %}

{% tab title="🔴 主題" %}

* [Binding from StateObject](/ios/swiftui/view/state/binding/binding/binding-from-stateobject.md)
  {% endtab %}

{% tab title="📗 參考" %}

* [ ] [How to initialize @StateObject with parameters in SwiftUI](https://sarunw.com/posts/how-to-initialize-stateobject-with-parameters-in-swiftui/)
* [ ] Sarun ⟩ [Should we manually call @StateObject initializer](https://sarunw.com/posts/manually-initialize-stateobject/)
  {% endtab %}

{% tab title="🔸 定義" %}
{% hint style="info" %} <mark style="color:purple;">**StateObject**</mark> 是一個 [property wrapper](/ios/swift/type/prop/wrapper.md)，它內含的資料一定要遵循 [ObservableObject](/ios/swiftui/view/state/observable-object/observableobject.md) 協定。
{% endhint %}

```swift
@frozen @propertyWrapper 
struct StateObject<ObjectType> where ObjectType : ObservableObject
```

{% endtab %}

{% tab title="📘 手冊" %}

* [SwiftUI](https://developer.apple.com/documentation/swiftui) ⟩&#x20;
  * View ⟩ [State Modifiers](https://developer.apple.com/documentation/swiftui/view-state) ⟩
    * [environmentObject(\_:)](https://developer.apple.com/documentation/swiftui/view/environmentobject\(_:\))
  * [State and Data Flow](https://developer.apple.com/documentation/swiftui/state-and-data-flow) ⟩
    * [StateObject](https://developer.apple.com/documentation/swiftui/stateobject) (<mark style="color:red;">**struct**</mark>)
    * [ObservedObject](https://developer.apple.com/documentation/swiftui/observedobject) (<mark style="color:red;">**struct**</mark>)
    * [EnvironmentObject](https://developer.apple.com/documentation/swiftui/environmentobject) (<mark style="color:red;">**struct**</mark>)
* [Combine](https://developer.apple.com/documentation/combine) ⟩&#x20;
  * [ObservableObject](https://developer.apple.com/documentation/Combine/ObservableObject) (protocol)
    {% endtab %}

{% tab title="👥 相關" %}

* [ObservableObject](/ios/swiftui/view/state/observable-object/observableobject.md)：declare an <mark style="color:yellow;">observable object</mark> [type](/ios/swift/type.md).
* [@Published](/ios/swiftui/view/state/observable-object/published.md)：declare a [published value](/ios/swiftui/view/state/observable-object/published-value.md) in an [observable object](/ios/swiftui/view/state/observable-object/observableobject.md) type.
* <mark style="color:purple;">@StateObject</mark>：initialize an [observable object](/ios/swiftui/view/state/observable-object/observableobject.md).
* is [property wrapper](/ios/swift/type/prop/wrapper.md).
* wraps an object that conforms to [ObservableObject](/ios/swiftui/view/state/observable-object/observableobject.md).
* [＠Binding](/ios/swiftui/view/state/binding/binding.md) can be [created](/ios/swiftui/view/state/binding/binding/binding-from-stateobject.md).
* [data model](/ios/master/term/data-model.md)：the [source of truth](/ios/master/term/source-of-truth.md) of your [app](/ios/swiftui/app.md).
  {% endtab %}
  {% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lochiwei.gitbook.io/ios/swiftui/view/state/object/stateobject.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
