为什么给定负值时我的程序会崩溃?
好吧,我很困惑,所以希望各位朋友能帮帮我。我正在开发一个使用 Cocos2D 的项目,最新版本(.99 RC 1)。我制作了一些玩家对象和一些按钮来改变对象的生命。但奇怪的是,当我尝试将它们的生命值改变-5 时,代码崩溃了。或者除 -1 之外的任何负值。
直接,但是当 NSnumber 为 -5 时,它甚至不会被调用,它会在 NSlog 语句处崩溃。那么……这是怎么回事?
通过更好地保留变量来解决它。谢谢你!
Alright, I am very confused, so I hope you friends can help me out. I'm working on a project using Cocos2D, the most recent version (.99 RC 1). I make some player objects and some buttons to change the object's life. But the weird thing is, the code crashes when I try to change their life by -5. Or any negative value for that matter, besides -1.
Straight forward, but when the NSnumber is -5, it doesn't even get called, it crashes at the NSlog statement. So... what's up with that?
Solved it by retaining the variable better. Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的。我再说一遍。访问器是你的朋友。使用它们。总是。注意:是的,我知道 Apple 建议不要在 init 和 dealloc 中使用它们,但在 15 年来,这从来没有给我带来过问题,而且不使用它们也没有。就像这个例子一样。有时您不想使用它们,但这些时间比您想要使用它们的时间要少得多。)
在您的buttonText方法中:
您应该执行以下操作:
看一下您的代码并了解如何分配/copy/retain 需要与release/autorelease 平衡。乍一看,你确实搞砸了内存管理。
OK. I will say this again. Accessors are your friends. Use them. Always. NOTE: Yes I know Apple recommends not using them in init and dealloc but in 15 years, this has NEVER once caused an issue for me and NOT using them has. As in this case. There are times when you do NOT want to use them, but those times are much less than the times you DO want to use them.)
In your buttonText method:
You should be doing a:
Take a look at your code and understand how alloc/copy/retain need balanced with release/autorelease. At first glance, you are really messing up on the memory management.
好吧,您的部分问题是您没有在任何地方使用符号“self.lifeChange”,这意味着您分配给
lifeChange
属性的 NSNumber 对象永远不会保留。这意味着 NSNumber 对象可能会随机死亡。更改为 self.lifeChange 并查看是否有帮助。
Well, part of your problem is that you are not using the notation "self.lifeChange" anywhere which means that the NSNumber objects you assign to the
lifeChange
property are never retained. This means the NSNumber object may die at random.Change to
self.lifeChange
and see if that helps.