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

Set @State var from another class

Forums > SwiftUI

Good morning

In a view I have several textfields for entering user information...which are set as empty string by default.

@State var name: String = ""
...
...
TextField("Name", text: $name)

When the app is launched through an appleEvent I can set the initial value with:

let kName = name ... struct BarcodeView: View { @State var name: String = kName

The variable name is set in another class where the event is received....and the view is most probably not initialized....

But when the application is running and it receives another appleEvent the changes are not reflected... So how can a @State var be set from another class?

thanks in advance richard

   

Think you might want to look at @EnvironmentObject or @ObservedObject. @State is for that view (which is why mark them as private.

Check out What’s the difference between @ObservedObject, @State, and @EnvironmentObject?

   

@Nigel has the correct answer.

I think of @State variables as light switches in a single room. The brightness in a room is controlled by the switches in that room. But those light switches are Private to that room. You cannot operate them if you are in a different room.

However, if you want to setup a solution to control ALL the switches in the entire house, you would NOT implement this solution using light switches in a single room. Instead, you'd probably opt for something more global. Something available in all the rooms of your house.

What objects are available to ALL the rooms in your house?

That's what @EnvironmentObject or @ObservedObjects do for you! These are objects that are available to all the rooms in your house.

   

Good morning

This article explains it very well: https://www.hackingwithswift.com/quick-start/swiftui/how-to-use-observedobject-to-manage-state-from-external-objects

Though...I can't use @ObservedObject in the AppDelegate class where the event manager receives the URL parameters from the browser...

class Address: ObservableObject {
    @Published var name = ""
    @Published var address = ""
    @Published var zip = ""
    @Published var city = ""
}

@main
struct BarcoderApp: App {
    @NSApplicationDelegateAdaptor private var appDelegate: AppDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        Settings {
          PreferencesView()
        }
    }
}

class AppDelegate: NSObject, NSApplicationDelegate {
    @ObservedObject var address: Address

    open func applicationWillFinishLaunching(_ notification: Notification) {
        initializeURIOptions()
    }

    fileprivate func initializeURIOptions() {
        let appleEventManager = NSAppleEventManager.shared()
        appleEventManager.setEventHandler(self, andSelector: #selector(handleGetURLEvent(event:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
    }

    @objc fileprivate func handleGetURLEvent(event: NSAppleEventDescriptor?, withReplyEvent replyEvent: NSAppleEventDescriptor?) {
     ....
     ....
     }

   

Hmm...also no success with this approach:

https://stackoverflow.com/questions/62998695/how-to-confirm-observableobject-for-an-appdelegate

The main problem is how to get data from AppDelegate into a specific view....

   

Hacking with Swift is sponsored by Emerge

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Find out more

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.