I am experimenting with a simple game. Just a few buttons and text being displayed.
I wanted to completely separate the game engine from views, view controllers, etc. As such, I defined it in a separate file and class called GameEngine.
I declare and intialize a GameEngine instance in the AppDelegate like this:
#import "GameEngine.h"
GameEngine *this_game; //It's global!
@interface ...{
...
// this_game is not declared here at all
...
}
//No getter/setter defined for this_game
The AppDelegate implementation looks something like this:
#import "MyGameAppDelegate.h"
@implementation ...
// this_game not synthesized
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after app launch
this_game = [[GameEngine alloc] init];
this_game.managedObjectContext = self.managedObjectContext;
[this_game initialize_data];
[window addSubview:game_vc.view]; // Display the primary application view
[window makeKeyAndVisible];
}
...
-(void)dealloc{
...
[this_game release];
...
}
OK, with that out of the way, this is what happens in the primary view controller’s header file:
#import "GameEngine.h"
extern GameEngine *this_game;
// No other reference to this_game in the .h file
And now the code in .m:
-(void)viewDidLoad{
...
NSLog([this_game test], nil); //Just a quick "I am here" test
...
}
This is all well end fine and I can call methods from the global this_game object all day long from various points in the program. It works.
The question really is about how “proper” or proper in the context of accepted practice for Objective-C, if you will, this approach might be?
Is this a bad idea? Why?
Is there a better way? Why is it better?
My intent, BTW, is to separate GameEngine code in order to make it easier to reuse for both this platform and other mobile platforms. All the native windowing and UI stuff needs to stay away from game logic.
Thanks,
-Martin
I totally agree with you in separating game logic code from all GUI related stuff is alway a good idea 🙂 I think your approach seems fine at first view, but 2 questions come into my mind:
1.) Why don’t you use a singleton? So you don’t have to use C code in your Obj-C project and you can always extend your application if you need to care about special situations when running on simulator or you want to use mock ups for testing or what ever. Have a look at Singletons, AppDelegates…. There is a nice little header file SynthesizeSingleton.h I used in my projects quite often.
2.) If your answer to 1.) is “as mentioned because I want to run it on different systems…”, then I suggest to implement your GameEngine class as C or C++. Thus migration to other platforms will be easier.