Cocos2d: CCSprite initWithFile in CCSprite subclass crashes(Cocos2d:CCSprite 子类中的 CCSprite initWithFile 崩溃)
问题描述
我有自定义 CCSprite 子类的 cocos2d 项目:
I have cocos2d project with custom CCSprite subclass:
MyCustomSprite.h:
MyCustomSprite.h:
#import "cocos2d.h"
@interface MyCustomSprite : CCSprite
@end
MyCustomSprite.m:
MyCustomSprite.m:
#import "MyCustomSprite.h"
@implementation MyCustomSprite
- (id)init
{
self = [super initWithFile:@"index.png"];
return self;
}
@end
由于某些奇怪的原因,这段代码会因EXC_BAD_ACCESS"而崩溃.
For some strange reason, this code will crash with "EXC_BAD_ACCESS".
但尽管如此,如果我像往常一样初始化超级,然后从 CCSprite 的 initWithFile 和 initWithTexture 编写代码,它会正常工作:
But in spite of this, if i init super as ususal and then write code from CCSprite's initWithFile and initWithTexture, it will work fine:
self = [super init];
if (self) {
// Code from CCSprite.m - initWithFile
CCTexture2D *texture = [[CCTextureCache sharedTextureCache] addImage: @"index.png"];
CGRect rect = CGRectZero;
rect.size = texture.contentSize;
// Code from CCSprite.m - iniWithTexture
[self setTexture:texture];
[self setTextureRect:rect];
return self;
}
第一个示例崩溃的原因是什么,第二个没有,它们之间有什么区别?
What's the reason that the first example crashes, and second not and what's the difference between them?
感谢您的回答!
推荐答案
好吧,原因是 CCSprite 设计不好.如果我们查看 CCSprite.h,我们可以发现:
Ok, the reason is bad CCSprite design. If we look to CCSprite.h, we can find:
-(id) initWithTexture:(CCTexture2D*)texture rect:(CGRect)rect
{
NSAssert(texture!=nil, @"Invalid texture for sprite");
// IMPORTANT: [self init] and not [super init];
if( (self = [self init]) )
}
这就是原因.此方法调用 [self init]
代替 [super init]
,并创建递归 ([self init]-[super InitWithFile:]-[self initWithTexture]-[self init]-...)
.
And thats the reason. Instead of [super init]
this method calls [self init]
, and creates recursion ([self init]-[super InitWithFile:]-[self initWithTexture]-[self init]-...)
.
.
因此,解决此问题的最简单方法 - 只需将您的 init 方法重命名为其他名称(例如initialize")并调用它而不是 init:[[MyCustomSpritealloc] 初始化]
.
So, the simplest way to solve this problem - just re-name your init method to something else (for example "initialize") and call it instead of init: [[MyCustomSprite
alloc] initialize]
.
这篇关于Cocos2d:CCSprite 子类中的 CCSprite initWithFile 崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Cocos2d:CCSprite 子类中的 CCSprite initWithFile 崩溃
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- android 4中的android RadioButton问题 2022-01-01