lundi 27 novembre 2023

Having trouble to design the data pattern in swiftui

I am creating a camera app I have a CameraService which is an ObservableObject and it runs the session. and update some UI according to session status.Then I inject it using .envrionmentObject()

in camera service I have a SettingHolder, which is also an ObservableObject, it inits using the deviceinput variable from the session. It contains the settings status of the camera, users can change it and on screen.

Basically it works like that:

class CameraService:ObservableObject{
   @Published var xxxxxxx
   var settingHolder:SettingHolder?
   func createHolder(){
       settingHolder = SettingHolder(deviceinput)//variable in service
   }
}
class SettingHolder:ObservableObject{
   @Published var focusMode = .lock//view use this to display
   ...
   var input//get from outside
   func changeFocus(){}//using input to change focus
}

But to make the @Published var in SettingHolder can update the view, I have to pass the object from upper view instead of using @EnvironmentObject, and I have use a weird way to init my view

@StateObject var service:CameraService
@StateObject var holder:SettingHolder
    init(service:CameraService){
        self._service = StateObject(wrappedValue: service)
        self._holder = StateObject(wrappedValue: service.settingHolder)
    }

I know it is a bad way using singleton and this post also suggest do not nest the ObservableObject post. But I don't know how to find a better way. So confused about this part.

Aucun commentaire:

Enregistrer un commentaire