|
So SwiftUI in 2023 makes it easier than ever to build your app using the MVVM architecture, thanks to We can use How would you guys do to save the app state in an iOS App, in order to have the same settings back even after killing and relaunching the app ? So far I made this, and it works, but it's quite a lot of boiler plate code and I don't even know if making a macro is possible :
|
|
I also noticed that this line works on Is this normal behavior ? |
|
|
|
How come doesn't this work ? I believe we could do a macro with it, but the code doesn't even compile. Error : Cannot find '
|
|
Apparently, the only way to get this work is this, and since the same class encapsulates everything, it would be possible to make a macro :
|
|
|
|
Unfortunately the code above is a memory leak because View structs have no lifetime so the object is lost and re-init over and over again every time ContentView is init. Instead of attempting to shoe-horn your view data into classes it is better to embrace the SwiftUI architecture and keep your view data in the View struct hierarchy. In Data Essentials in SwiftUI at WWDC 2020 at 20:50 they said "Views are very cheap, we encourage you to make them your primary encapsulation mechanism". In other videos they explain that View structs arent actually the view layer at all, SwiftUI diffs the structs after every change and then uses the diff to init/update/deinit UIKit objects, hence the View structs are actually a view model already, thus SwiftUI's design is MVVM already so it doesn't really make sense to layer your own view data objects on top. Especially since the whole point of structs is to eliminate the kind of consistency bugs typical of objects and their shared mutable state. You can still have seperation and testability in SwiftUI without objects, you can group related state vars in a custom @State struct and use mutating func for logic. You can also extract your logic into a testable func that takes params and returns a result. That way your mutable state can be both in an @State in the view struct and in a var in your test and the problem is solved! Regarding @AppStorage, it's best to use it as a source of truth in highest common parent in the hierarchy, pass it down as a let for read access or binding for read/write, use onChange for external actions. If you need deep access you can put its value or its binding in the Environment. Exactly the same as you would do for @State values. |
SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until February 9th.
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.