简体   繁体   中英

Calling class method on a class parameter

I need to call a class method to run a Cocos2D scene. I have a game controller in which I will pass in different states (or layers for those familiar with Cocos2D). See the code below:

-(void)startGameWithState:(Class)s {
    [[CCDirector sharedDirector] runWithScene: [s scene]];
}

The thing is, this is working fine but generates the following warning:

No '+scene' method found

As best as possible, I want to avoid having warnings so how do I fix this?

Update: This is what I did.

-(void)changeStateTo:(Class <GameState>)s {
    [[CCDirector sharedDirector] runWithScene: [s scene]];
}

By having the GameState protocol define the +scene method, I don't get any warnings.

基本上,只需使用scene类方法声明一个协议或抽象类,以便编译器知道它的存在。

It's telling you that your generic type -- Class -- doesn't have a method called scene . If you're passing in states/layers, those must be of some actual class, right? You need to tell the compiler what class s actually is so that it can find the scene method in it.

If you will always pass concrete class the write

-(void)startGameWithState:(ConcreteClass*)s

If you will use different classes without any hierarchy between them use id to avoid the warning

-(void)startGameWithState:(id)s

The second method is not very good because if you will pass the incorrect class object to this method you'll get runtime error. But at the compiling state everything will be fine

If you know that every class passed will be derived from some base class with a +(id) scene method then pass the base class:

-(void)startGameWithState:(BaseClass*)s

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM