如何从另一个类访问实例

时间:2014-03-10 05:01:29

标签: ios objective-c oop cocos2d-iphone

提前感谢您的帮助!

我是OOP的新手,所以这个问题可能非常基本,但我已经搜索了几个小时但仍无法找到一个好的解决方案。

我在项目中使用Cocos2d和Box2d。在我的GameLayer.mm文件中,我有一个标签来显示当前分数。还有一个源自CCSprite的自定义精灵。

现在,当精灵“isDead”的属性更改为true时,我想从我的自定义精灵类增加当前分数。如下:

- (void) setIsDead
{
    isDead = 1;
    // then increment score
}

我的问题是如何从这个子类增加分数?我无法从此子类访问GameLayer.mm的实例或实例方法。我试图将增加得分的功能从实例方法改为类方法,并将得分作为全局实例,但后来我得到了重复错误。

感谢您的任何建议!

2 个答案:

答案 0 :(得分:1)

这是我喜欢的另一种方法:代表。

首先,转到自定义CCSprite标头并创建新协议。基本上,添加这个:

@protocol MyCustomDelegate

-(void)spriteGotKilled:(CCSprite*)sprite;

@end

接下来,您需要修改自定义CCSprite以存储其委托。您的界面如下所示:

@interface MySprite {
  id delegate;
}

@property (retain,nonatomic) id delegate;

现在转到GameLayer.h并使其实施协议:

@interface GameLayer : CCLayer <MyCustomDelegate>

接下来在你的图层中实现协议方法:

-(void)spriteGotKilled:(CCSprite*)sprite {
  NSLog(@"%@ got killed!",sprite);
}

最后,转到setIsDead方法:

-(void)setIsDead {
  isDead = 1;
  // Check if we have a delegate set:
  if ([self delegate] != nil) {

    // Check if our delegate responds to the method we want to call:
    if ([[self delegate]respondsToSelector:@selector(spriteGotKilled:)]) {

      // Call the method:
      [[self delegate]spriteGotKilled:self];

    }

  }

}

创建精灵时,必须将图层设置为其委托。像这样:

MySprite *sprite = [[MySprite alloc]init];
[sprite setDelegate:self];

现在,只要你的精灵死掉,你的图层就会调用spriteGotKilled

答案 1 :(得分:0)

您可以在此处使用观察者设计模式,观察者可以在其中监听事件并相应地执行操作。

所以在你的GameLayer.mm中,在init函数中添加观察者:

[[NSNotificationCenter defaultCenter] addObserver:self
        selector:@selector(receiveIsDeadNotification:) 
        name:@"SpriteIsDeadNotification"
        object:nil];

并添加一个函数:

- (void) receiveIsDeadNotification:(NSNotification *) notification
{

    if ([[notification name] isEqualToString:@"SpriteIsDeadNotification"])
        //update your label here
}

并在自定义精灵中,在setIsDead方法中添加以下行

-(void) setIsDead{
     isDead =1;
     [[NSNotificationCenter defaultCenter] 
        postNotificationName:@"SpriteIsDeadNotification" 
        object:self];
}

还记得删除GameLayer.mm

的dealloc中的观察者
[[NSNotificationCenter defaultCenter] removeObserver:self];

此模式将减少代码中的耦合,因为一个类的实例不会尝试访问另一个类的方法。

相关问题