WWDC24 SALE: Save 50% on all my Swift books and bundles! >>

@StateObject question?

Forums > SwiftUI

I am working on the ultimate portfolio course.

Trying to understand why we are creating a StateObject by hand vs just instantiating in UltimateProtfolioApp file

 @StateObject var dataController: DataController

    init() {
        let dataController = DataController()
        _dataController = StateObject(wrappedValue: dataController)
    }

VS

@StateObject var dataController: DataController()

Thanks for the help in understaning this

3      

Which video are you upto, or have you watched all the tutorials that are currently available?

If I remember correctly Paul mentions why it is done this way in one of the later (more recent) videos.

4      

First you would do

@StateObject var dataController = DataController()

and Paul do mention in his video Designing a great model why he did it the other way

The first thing we’re going to add to DataController is an initializer, telling it to load that “Main” data model we defined earlier. However, we’re going to add a little flexibility here: to allow us to preview data more easily, we’re going to add an inMemory Boolean when creating our data controller. When this is set to true, we’ll create our data entirely in memory rather than on disk, which means it will just disappear when the application ends – it’s great for previewing in SwiftUI, but also helpful for writing tests.

And also later on in Offering in-app purchases, part 1

Now, way back when we built the very first part of this app you might remember I said we were going to create our DataController instance inside an initializer, because trying to write @StateObject var dataController = DataController() would cause problems later on.

Well, “later on” is now: we need to create two @StateObject properties, where one depends on the other – our unlock manager needs to be given the data controller in its initializer. This isn’t possible if you create your state objects directly in the property declaration, but it’s trivial when using an initializer.

4      

Hacking with Swift is sponsored by Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.