我想要在App Delegate中访问我的运行场景。问题是,[[CCDirector sharedDirector] runningScene]
返回CCScene
个对象,而不是我的场景MyMainScene
的实际类。如果我尝试调用我的任何自定义方法,我会得到:
-[CCScene customMethod]: unrecognized selector sent to instance 0x156bedc0
我尝试过像这样的
CCScene *scene = [[CCDirector sharedDirector] runningScene];
MyMainScene *mainScene = (MyMainScene*)scene;
[mainScene customMethod];
但这没有效果。上面的mainScene
对象仍然返回类名CCScene
,并且会在运行时崩溃。
我也尝试过动态投射,如Objective-C dynamic_cast?所示。使用动态转换我不会崩溃,但该方法始终返回null。
AppController实现
#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标题
#import <Foundation/Foundation.h>
#import "cocos2d.h"
@interface IDFAMainScene : CCNode {
}
-(void)customMethod;
IDFAMainScene实施
#import "IDFAMainScene.h"
@implementation IDFAMainScene
-(void)didLoadFromCCB{
[self customMethod];
}
-(void)customMethod{
NSLog(@“custom method called");
}
上面的应用程序将编译。它会加载IDFAMainScene文件,因为customMethod
被调用并从"custom method called"
记录didLoadFromCCB
,但是当它尝试从customMethd
中的强制转换对象调用applicationDidBecomeActive...
时它崩溃了,错误
-[CCScene customMethod]: unrecognized selector sent to instance 0x175b7e50
答案 0 :(得分:2)
loadAsScene方法返回一个CCScene对象,并将自定义类作为唯一的子对象。因此,您需要更改此代码以获取您的自定义类,如下所示(我也转换为点表示法,因为我喜欢尽可能传播它):
CCScene *scene = [CCDirector sharedDirector].runningScene;
IDFAMainScene *mainScene = (IDFAMainScene*)scene.children.firstObject;
[mainScene customMethod];