I have a singleton implemented in my app, but I’ve run into a problem when I switch between view controllers.
My app starts in one view controller, MainMenu, then switches to the Game view controller when the menu selection is made. I have a singleton class in the Game VC that is the object manager (called World) for the game. It loads content based on the menu selection in MainMenu. I can load up and quit back to the MainMenu VC fine. Singleton works fine. When I select from the MainMenu again (going from MainMenu VC to Game VC), my app crashes cause of an NSAssert to prevent the singleton World from allocating a second time, which is intentional.
How can I switch back to the Game VC without it trying to reinitialize my singleton?
Essentially, I want to skip the [[world alloc] init] line in my Game VC’s init method. I can’t figure out how to do this properly… it would need to be able to be handled the first time (when World doesn’t exist) or any subsequent time (when World already exists as a singleton). I’ve tried if (!world) and that doesn’t work.
This also begs the question… did I implement my singleton in the right place? Should I perhaps put it in the MainMenu instead? I just want to avoid it trying to reinitialize / reallocate the singleton when I switch between the two VCs.
If this helps, I’m exiting the Game VC by using [self.view removeFromSuperview]; Should I do it a different way?
I was able to solve this by indeed moving the singleton initialization up into the MainMenu view controller as I was thinking. In my design,
initfor that VC is only called once upon app startup, whereas the custominitmethod in my Game VC gets called each time I switch to it.Not sure if that’s the optimal design I should be using, but it works for now.