Search code examples
iphonexcodeuiviewcontrollerquartz-2d

Implementing a main menu for iPhone game - how to get back to the Main Menu?


Apologies for the long post and I hope it makes some sense to someone out there.

I have written an iPhone game (in Quartz 2d) which uses the following structure :

  • App delegate loads a view controller called gameviewcontroller and its associated view
  • In the "View did load" method, the gameviewcontroller starts up and initiates a Game Controller class (NSObject). It also starts a timer on a "Game Loop" method in the Game Controller. Finally it tells the Game Controller to use the same view as the gameview controller (which is a custom UIView).

This all works fine. I am now trying to integrate a Main Menu for the game. So far I have done the following :

  • Created a new View Controller called "Main Menu" with an associated NIB. In the NIB I have created my main menu with a "Start" button.
  • Altered the app delegate to load the Main Manu NIB and display its view.
  • Set a method so that when the button is pressed it then loads the gameviewcontroller (which effectively starts the game).

So far so good - pressing the "start" button starts the game. But.....

The problem is now that I can't find a way for the Game Controller to call up the Main Menu class (e.g for when game is over). I can't use "self dismissModalViewController" as Game Controller is an NSObject class and not a view controller. How can I get the Game Controller to pull up my Main Menu ?

Thanks all for reading,

Martin


Solution

  • If you have your menu object still living just call its "dissmisModalViewController". for example [[MainMenu getInstance] dismissModalViewControllerAnimated:YES]; where getInstance returns your object or have it stored in GameController as property, so when you create GameController from your MainMenu or GameViewController just assign itself as his property gameInstance.mainMenu = self;

    How-to make getInstance method:

    You could either use Singleton pattern ( you can get one from apple dev site ) or if you manually create MainMenu you could just remember self in some global variable and getInstance would be class method, something like that:

    @interface MainMenu : UIViewController 
    { 
    } 
    + (MainMenu*) getInstance; 
    @end 
    

    and in implementation

    MainMenu *singleInstance; 
    @implementation MainMenu 
    - (id)init 
       { 
         if((self = [super init])) 
         { 
           singleInstance = self; 
         } return self; 
        } 
    
     + (MainMenu*)getInstance 
     { 
        return singleInstance; 
     } 
    @end;
    

    Hope this helps,

    Krzysztof Zabłocki