我想在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");
}
上面的应用程序将编译。可以在调用
customMethod
并从"custom method called"
记录didLoadFromCCB
时加载IDFAMainScene文件,但是当它尝试从customMethd
中的转换对象调用applicationDidBecomeActive...
时,它会崩溃并报错-[CCScene customMethod]: unrecognized selector sent to instance 0x175b7e50
最佳答案
loadAsScene方法返回一个CCScene对象,其自定义类是其唯一的子级。因此,您需要按以下方式更改此代码以获取您的自定义类(我还转换为点表示法,因为我希望尽可能地传播它):
CCScene *scene = [CCDirector sharedDirector].runningScene;
IDFAMainScene *mainScene = (IDFAMainScene*)scene.children.firstObject;
[mainScene customMethod];
关于ios - Cocos2d V3 iOS-如何从App Delegate访问runningScene,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24759662/