0

In my I've defined a CCLayer like this:

@interface MyLayer : CCLayer {
    CCLayer * referenceLayer; 
}

How should I declare it to use it in +(CCScene *) scene ?

Like this ?

@property (nonatomic, retain) CCLayer *referenceLayer;
el.severo
  • 2,202
  • 6
  • 31
  • 62
  • Prefer to rewrite the code so that you can do it in the -(id) init method. – CodeSmile Feb 02 '12 at 18:26
  • @LearnCocos2D: I'm sorry but I didn't get what you mean; What I'm trying to achieve is to get some sprites from another layer... Do you know any possibility rather than `CCSprite *sprite = (CCSprite *)[referenceLayer getChildByTag:kTagNumber];` ? – el.severo Feb 02 '12 at 22:12

1 Answers1

1

Since + (id)scene is a class method, you cannot access an ivar/property from within it. One possible solution is having a static variable in your layer.m file, like in the following snippet:

static CCScene* _scene = nil;

+ (id)scene {
   if (_scene == nil) {
      _scene = [[CCScene node] retain];
      //-- further scene initializaion
   }
   return _scene;
 }

This simple approach has a drawback: you can only have one such layer around.

sergio
  • 68,819
  • 11
  • 102
  • 123
  • what about [this example](http://stackoverflow.com/questions/9076699/accessing-an-object-from-class-type-method-in-iphone-cocos2d)? – el.severo Feb 02 '12 at 18:16
  • it would also work, you only need to define: `+(id)scene:(CCLayer*)l` instead of `+ (id)scene`. In this case you will need to `alloc-init` the layer in advance and `scene` cannot act as a factory method. – sergio Feb 03 '12 at 16:54
  • Can you update your answer? Actually I'm trying to add the `bLayer` as child to the `referenceLayer`; do you think that's possible? – el.severo Feb 03 '12 at 16:59