Reputation: 158
I am currently programming a Cocos2d game for iOS.
In this game, I created a GameState singleton in order to save my game status (items details and positions, duration, score, etc.).
My main CCScene contains a -(void) saveData:
method which, when invoked from within the running game (player hit the backToMenu button -> -(void) backToMenu:
), performs accordingly:
We are sent back to the menu where, because GameState.sharedState -> PLAYING = true
, a Resume button appear and allows us to resume the current game.
Until here, it works expectedly.
Now, how could I invoke the method -(void) backToMenu:
from the appController
's method applicationWillEnterBackground
?
I tried invoking the [[CCDirector sharedDirector] runningScene]
but it crashes somehow, also on resume, which means I am not even sure I saved proper contents.
Thanks in advance for your help.
Upvotes: 3
Views: 519
Reputation: 158
Update: Just found about this.
Could I, for example, create an NSNotification
in the appController's applicationWillEnterBackground
method, then handle it within my CCLayer object in which I'd add an NSObserver in its init
method to receive such notifications?
Upvotes: 0
Reputation: 22042
Add this in AppDelegate.h :
@class CCLayer;
@interface AppController : NSObject <UIApplicationDelegate, CCDirectorDelegate,UIGestureRecognizerDelegate>
{
CCLayer *mCurrentLayer;
}
@property (nonatomic, retain) CCLayer *currentLayer;
Add this in AppDelegate.mm :
@implementation AppController
@synthesize currentLayer = mCurrentLayer;
In your Layer init class use this. In all scene method.
@implementation MyMainMenu
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
MyMainMenu *layer = [MyMainMenu node];
AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
app.currentLayer = layer;
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
You can check anywhere in project..
In appDelegate
-(void) applicationDidEnterBackground:(UIApplication*)application
{
if([self.currentLayer isKindOfClass:[MyMainMenu class]])
MyMainMenu *mm = (MyMainMenu*) self.currentLayer;
[mm calFunction];
}
In other class:
-(void)callUpdateButtonsInLayer
{
AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
if([app.currentLayer isKindOfClass:[MyMainMenu class]])
{
MyMainMenu *mm = (MyMainMenu*) app.currentLayer;
[mm calFunction];
}
}
Upvotes: 1