Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 从CCNode继承的init方法_Objective C_Cocos2d Iphone_Ccnode - Fatal编程技术网

Objective c 从CCNode继承的init方法

Objective c 从CCNode继承的init方法,objective-c,cocos2d-iphone,ccnode,Objective C,Cocos2d Iphone,Ccnode,我有一个关于在从CCNode继承的Player类中创建自定义init方法的问题。不确定是否需要改为采用不同的路线并创建类方法: +(id)添加sprite:(CCSprite*)sprite和spritebatchnode:(CCSpriteBatchNode*)spriteBatch 更多的类方法 在Player类中,我有一个指定的init方法,以及一些方便的init方法。 -(id)init -(id)initWithSpriteBatchNode:(CCSpriteBatchNode*)s

我有一个关于在从CCNode继承的Player类中创建自定义init方法的问题。不确定是否需要改为采用不同的路线并创建类方法:

+(id)添加sprite:(CCSprite*)sprite和spritebatchnode:(CCSpriteBatchNode*)spriteBatch
更多的类方法

Player
类中,我有一个指定的init方法,以及一些方便的init方法。
-(id)init
-(id)initWithSpriteBatchNode:(CCSpriteBatchNode*)spriteBatch
-(id)initWithSprite:(CCSprite*)sprite和spritebatchnode:(CCSpriteBatchNode*)spriteBatch//指定的初始化方法

当我在我的级别类中实例化这个类时,我不能直接调用任何自定义init方法。我要做的是:

Player*Player=[Player节点]
[player initWithSprite:sprite和spriteBatch节点:spriteBatch;]//不确定这是否正确或是否会泄漏内存

我认为这两种方法中的任何一种都应该起作用,因为它们只是在实例级别上做相同的事情,而在名称级别上做其他方法


请注意。

这里的问题是您的
Player
继承自
CCNode
,它不为精灵或批处理节点提供功能,仅仅因为
CCNode
只是一个逻辑节点

如果您从
CCSprite继承
,则可以轻松完成所需的操作:

@interface CCPlayer : CCSprite
{

}

- (id) initWithSpriteBatchNode: (CCSpriteBatchNode*) spriteBatch;

@end

@implementation CCPlayer

- (id) initWithSpriteBatchNode: (CCSpriteBatchNode*) spriteBatch
{
  if ((self = [super initWithSpriteBatchNode:spriteBatch]))
  {
    // custom code
  }

  return self;
}

@end
现在你就能做到了

CCPlayer *player = [[[CCPlayer alloc] initWithBatchNode:batchNode] autorelease];
[somewhere addChild:player];
当然,如果你的玩家精灵在逻辑上是一个单一的精灵,那么这是可行的,如果你有,让我们说更多的碎片,那么你将需要使用合成:

@interface CCPlayer : CCNode
{
  CCSprite *body
}

-(id)init;

@end

@implementation CCPlayer

-(id)init
{
  if ((self = [super init]))
  {
    body = [CCSprite spriteWith:...;
    [self addChild:body];
  }

  return self;
}

我想得太多了,弄糊涂了。Cocos2D有一个类方法,例如:
[CCNode]
方法

我可以有尽可能多的实例和类方法来创建自定义类的实例。它们只是方便的方法

而不是使用默认的继承方法:
Player*Player=[Player节点]=>基本上执行alloc/init

我可以使用我的一个自定义init方法:
Player*Player=[[Player alloc]initWithSpriteBatchNode:spriteBatch]autorelease]

[spriteBatch addChild:playerSprite]或其他什么…

查看您的代码消除了我的困惑、过度思考和困惑。我从CCNode继承是出于两个不同的原因。1) 我只想继承我需要的东西(保持objs亮),2)我将切换精灵,所以合成是我使用CCSprite的选择方法。我想我之前可能把自己搞糊涂了<代码>玩家*p=[玩家节点]同时执行alloc/init,因此我可以执行类似于
Player*p=[[Player alloc]init..]autorelease]的操作。实例方法和类方法不应该成为问题。类方法是方便的方法。谢谢,谢谢你的帮助。