Reputation: 9123
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.
Upvotes: 1
Views: 77
Reputation: 257719
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
}
Upvotes: 1