|
Good day together, iam pretty new at swift and also in this forum. First I say what I intend to do and then I show what I have done. After a FetchedRequest has been made, I would like to make the data records available for all views. I thought it would be best to create an EnvironmentObject that holds the data before passing it to each subview. Intermediate question: Is this a good approach? Or is there a better way. As I said, I chose the approach with the EnvironmentObject. Here is the code:
In the Codeblock below raise the Warning message: Accessing StateObject's object without being installed on a View. This will create a new instance each time.
I struggle on this the whole day. iam not sure i follow the right path. Of course I googled it. I found that it might be because I have to execute the fetch result in a view. The solution approach was that I also pass it to the window group. The answer was marked as "correct", but it still doesn't work. Does anyone have an idea or can tell me what I should do? Many thanks in advance and a happy new year |
|
Hi! In this case you cannot use
That is true so you have to refactor your class similar to this. This example passes in moc because you might pass in a different NSManagedObjectContext when previewing your SwiftUI vew. If this is not important to you then you can also just initialize a moc in the initializer and not pass it in.
Then you can use it something like this.
or you can inject AnimalManager to the environment and access it from there as well. |
|
@MrSwifty lets us know he's new to Swift:
Then asks about
And asks for feedback:
SwiftData vs CoreDataYes, there is a better way. It's not to use
Keep Coding!Highly recommend you try out the See -> Fun with SwiftData |
|
Thanks to you both. And a special thanks to Obelix. I like SwiftData. :) Everything works immediately. And most importantly, it works the way I want it to. |
SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.
Sponsor Hacking with Swift and reach the world's largest Swift community!
You need to create an account or log in to reply.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.