I am working on a card game, using a MainCoordinator (2 other coordinators that are irrelevant here) and a state machine with 14 states, and trying to navigate using NotificationCenter.default, but my observers are not catching the messages I post. There are 4 player positions, which I call Left, Up, Right, and Down. I am only showing the code for the Left player, to simplify and shorten.
In MainCoordinator.swift, I have:
class MainCoordinator: Coordinator {
var childCoordinators = [Coordinator]()
var navigationController: UINavigationController
let stateMachine: MyStateMachine
var nc = NotificationCenter.default
init(navigationController: UINavigationController) {
self.navigationController = navigationController
stateMachine = MyStateMachine(navController: navigationController, states: [...,PlayerLeftTurnState(),...])
}
func start() {
let vc = ViewController.instantiate()
vc.coordinator = self
if navigationController.topViewController != vc {
navigationController.pushViewController(vc, animated:false)
}
}
func subscribeToNotifications() {
nc.addObserver(self, selector: #selector(PlayerLeftTurnNotification), name: Notification.Name("playerLeftTurnNotification"), object: nil)
}
@objc func PlayerLeftTurnNotification(notification: NSNotification) {
stateMachine.enter(PlayerLeftTurnState.self)
}
After I do my setup and deal the cards (in a Game.swift class), I try to post for the left player to take a turn
var nc = NotificationCenter.default
nc.post(name: Notification.Name("playerLeftTurnNotification"), object: nil)
This notification is not caught.
I tried adding a button to my main window, and having the IBAction post the same notification, but that is not caught either.
Any help greatly appreciated.
Bill