0
\$\begingroup\$

So I built my first game app, and it was a lot of fun. I'm really trying to expand on some of the ideas, but I'm running in to some serious variable scope issue. What I want to do is encapsulate a CCSprite as an instance variable, and then modify it in my "HelloWorldLayer"

In my header:

@interface HelloWorldLayer : CCLayer
{
    CCSprite *mySprite;
}

and in my HelloWorldLayer.m I run into the problem where if I try to do something like

- (id)init
{
   CCSprite mySprite = [CCSprite initWithFile:@"spriteFile.png"];
}

I run into either

  1. Memory management issues
  2. Variable scope issues (overwriting etc.)

What I want to do is be able to declare the sprite, and then change certain properties in other methods such as ccTouchesMoved. How can I do this?

P.S. I'm sorry if the code is a little rough around the edges, I have been writing Ruby for the last two weeks and I'm a little out of it with reference to objective.

\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

Your declaration is correct, however, your instantiation should not have the CCSprite class name in front. Just

mySprite = [[CCSprite spriteWithFile:@"spriteFile.png"] retain]

is fine. If you're using ARC, then you can leave out the retain.

I normally like to just use properties though so I can refer to them easier and also have the option of accessing the ivar from another class.

@interface HelloWorldLayer ()
@property (nonatomic, strong) CCSprite *mySprite;
@end

@implementation HelloWorldLayer
- (id) init {
    if ((self = [super init])) {
        self.mySprite = [CCSprite spriteWithFile:@"spriteFile.png"];
    }
    return self;
}

- (void) someMethodName {
    // You can do anything with the sprite anywhere else in the app.
    self.mySprite.position = ccp(200, 200);

    // You won't need to retain or release it anywhere in the implementation
    // as long as you're using ARC.
}
@end 
\$\endgroup\$
1
\$\begingroup\$

mySprite is declared as member variable. You redeclared again in the init function as local variable so it won't overwrite the member variable. I suggest you should not redeclare it again as local variable as you will use it in somewhere else.

You will need to retain varible created from initWith, e.g.,

 mySprite = [[CCSprite initWithFile:@"spriteFile.png"] retain];

You will need to release it when you no longer use it.

\$\endgroup\$
3
  • \$\begingroup\$ OK. Cool. I'll let you know how that works \$\endgroup\$ Jan 20, 2013 at 23:10
  • \$\begingroup\$ I'll need to release it when I no longer need it, how do I go about doing that? \$\endgroup\$ Jan 20, 2013 at 23:37
  • \$\begingroup\$ [mySprite release]; \$\endgroup\$
    – neo
    Jan 21, 2013 at 1:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .