Cocos2d:CCSprite 子类中的 CCSprite initWithFile 崩溃

Cocos2d: CCSprite initWithFile in CCSprite subclass crashes(Cocos2d:CCSprite 子类中的 CCSprite initWithFile 崩溃)

本文介绍了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 崩溃

基础教程推荐