简体   繁体   中英

How to pass an EnvironmentObject to an ObservedObject within that EnvironmentObject?

I have an EnvironmentObject called GameManager() that is basically the root of my app:

class GameManager: ObservableObject {
    @ObservedObject var timeManager = TimeManager()

Because there is a lot of code in it, I want to delegate certain tasks into seperate classes/files.

For example, I want to create a timer running every second. This could easily run inside GameManager() , but I want to delegate this to a seperate class called TimeManager() :

class TimeManager: ObservableObject {
    @EnvironmentObject var gameManager: GameManager
    var activeGameTimer: Timer?
    @Published var activeGameSeconds: Int = 0
    
    func start(){
        self.activeGameTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true){ _ in
            self.activeGameSeconds += 1  
        }
    }
}

Only problem is, TimeManager needs to have a reference to GameManager() - in order to react to certain events in my game.

However, there doesn't seem to be a way to pass GameManager() into TimeManager() .

Is there a smooth way to achieve this? If not, is there another way I should arrange what I'm trying to do?

If the solution is hacky, I would rather not do it.

First of all @ObservedObject and @EnvironmentObject are property wrappers designed for SwiftUI View not for other else, so using them in classes might be harmful or at least useless - they do not functioning as you'd expected.

Now the solution for your scenario is dependency injection (both types are reference-types so instances are injected as a references):

class GameManager: ObservableObject {
    var timeManager: TimeManager!

    init() {
       timeManager = TimeManager(gameManager: self)
    }
    // ... other code
}

class TimeManager: ObservableObject {
    var gameManager: GameManager

    var activeGameTimer: Timer?
    @Published var activeGameSeconds: Int = 0

    init(gameManager: GameManager) {
       self.gameManager = gameManager
    }

    // ... other code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM