开发者

Accessing a Sprite in Touch Event with Objective C

I am trying to make a sprite move to a point that is touched by the user. My problem is I declare the sprite inside my init like this:

CCSprite *ball = [CCSprite spriteWithFile:@"ball.png"                            
rect:CGRectMake(0, 0, 20, 20)];

and inside my touch event:

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{

I reference the ball and it says it's "undefined". Due to my understanding of scope in other languages I would hypothesize that I need to make "ball" a global variable, right? I have read that Global variables are typically "frowned upon" in objective-C. Why is this so? Is it memory related?

If you suggest something could you please let me know if 开发者_如何学CI need to deallocate it at the close of my app. I'm really a beginner in iOS development.

Any advice would be a huge help!


Global variables are not just frowned upon in Objective C, they are usually bad practice for most languages. It leads to poor program design.

Generally speaking, if you want an object to create and continue to access another object throughout its lifetime and not merely within a single method, you should assign it to an instance variable.

In this case, you appear to be using cocos2d - so it's likely that your scene should have a ball instance variable. You should release it (you don't call dealloc in Objective C) when your scene is deallocated, if not before.

If you are shaky with knowing when to release it, you'll probably want to read the Memory Management Programming Guide. For a start, if you want that instance variable to not crash your program, you'll need to retain that sprite.


Here's how to make a CCSprite globally available in your method file:

// in .h
@interface HelloWorld : CCLayer
{
    CCSprite *ball;
}

And then you can access "ball" inside the method file

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜