0

I’m wanting to access my running scene in the App Delegate. The problem is, [[CCDirector sharedDirector] runningScene] returns a CCScene object, rather than the actual class of my scene MyMainScene. If I try to call any of my custom methods, I get:

-[CCScene customMethod]: unrecognized selector sent to instance 0x156bedc0

I’ve tried casting like this

CCScene *scene = [[CCDirector sharedDirector] runningScene];
MyMainScene *mainScene = (MyMainScene*)scene;
[mainScene customMethod];

But this has no effect. The mainScene object above still returns a class name of CCScene, and will crash at runtime.

I’ve also tried dynamic casting, as suggested here Objective-C dynamic_cast?. With dynamic casting I don’t get a crash, but the method always returns null.


UPDATE - MORE CODE

AppController implementation

#import "cocos2d.h"
#import "AppDelegate.h"
#import “ IDFAMainScene.h”

@implementation AppController

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    // default code here
}

- (CCScene*) startScene {
    return [CCBReader loadAsScene:@“IDFAMainScene”];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {

    CCScene *scene = [[CCDirector sharedDirector] runningScene];
    IDFAMainScene *mainScene = (IDFAMainScene*)scene;
    [mainScene customMethod];

}

IDFAMainScene header

#import <Foundation/Foundation.h>
#import "cocos2d.h"
@interface IDFAMainScene : CCNode {

}

-(void)customMethod;

IDFAMainScene implementation

#import "IDFAMainScene.h"

@implementation IDFAMainScene

-(void)didLoadFromCCB{
    [self customMethod];
}

-(void)customMethod{
    NSLog(@“custom method called");
}

The above application will compile. It loads the IDFAMainScene file okay as customMethod gets called and logs "custom method called" from didLoadFromCCB, but when it then tries to call the customMethd from the cast object in applicationDidBecomeActive... it crashes with error

-[CCScene customMethod]: unrecognized selector sent to instance 0x175b7e50
Community
  • 1
  • 1
Graham Nicol
  • 264
  • 2
  • 14

1 Answers1

2

The loadAsScene method returns a CCScene object with your custom class as its only child. Hence you need to change this code to get your custom class as follows (I also converted to dot notation as I like to propagate it whenever possible):

CCScene *scene = [CCDirector sharedDirector].runningScene;
IDFAMainScene *mainScene = (IDFAMainScene*)scene.children.firstObject;
[mainScene customMethod];
CodeSmile
  • 64,284
  • 20
  • 132
  • 217