NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

@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

   

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.

1      

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.

1      

Hacking with Swift is sponsored by Instabug

SPONSORED Catch bugs as soon as they happen and know exactly why a crash occurred. Instabug's SDK grabs all the logs they need to fix bugs, crashes and performance issues in minutes instead of days. Get screenshots, device details, network logs, repro steps, and tons of other critical insights needed to resolve issues and prioritize product backlogs straight from your dashboard. It only takes a minute to integrate!

Get started now

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

Reply to this topic…

You need to create an account or log in to reply.

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.