简体   繁体   English

使用目标 C 访问 Sprite in Touch 事件

[英]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:我的问题是我在我的 init 中声明了 sprite,如下所示:

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?由于我对其他语言中的 scope 的理解,我假设我需要将“球”设为全局变量,对吧? I have read that Global variables are typically "frowned upon" in objective-C.我读过 objective-C 中的全局变量通常是“不受欢迎的”。 Why is this so?为什么会这样? Is it memory related?是否与 memory 相关?

If you suggest something could you please let me know if I need to deallocate it at the close of my app.如果您提出建议,请告诉我是否需要在我的应用程序关闭时取消分配它。 I'm really a beginner in iOS development.我真的是 iOS 开发的初学者。

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.全局变量不仅在 Objective C 中不受欢迎,对于大多数语言来说,它们通常是不好的做法。 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.一般来说,如果您希望 object 在其整个生命周期内创建并继续访问另一个 object 而不仅仅是在单个方法中,则应将其分配给实例变量。

In this case, you appear to be using cocos2d - so it's likely that your scene should have a ball instance variable.在这种情况下,您似乎正在使用 cocos2d - 所以您的场景很可能应该有一个 ball 实例变量。 You should release it (you don't call dealloc in Objective C) when your scene is deallocated, if not before.当你的场景被释放时,你应该释放它(你不要在Objective C中调用dealloc ),如果不是之前的话。

If you are shaky with knowing when to release it, you'll probably want to read the Memory Management Programming Guide .如果您不知道何时发布它,您可能需要阅读Memory 管理编程指南 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:以下是如何使 CCSprite 在您的方法文件中全局可用:

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

And then you can access "ball" inside the method file然后您可以访问方法文件中的“球”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM