Search code examples
iosobjective-ccocos2d-iphonensobjectccsprite

Adding a CCSprite (NSObject) to a MutableArray crash


I have a "bomb" CCSprite in its own class(If people who doesn't use cocos2d reads this, CCSprite is a NSObject pretty much).

The CCSprite file looks like this:

Bomb.h: 
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import <OpenAL/al.h>

@class HelloWorldLayer;

@interface Bomb : CCSprite {
    @private
    int length;


}
@property (readwrite) int length;

@end



Bomb.m:
#import "Bomb.h"


@implementation Bomb
@synthesize length = _length;

@end

I add it in my game layer (HelloWorldLayerlike a pro) with @class Bomb; in .h, and I import the Bomb.h in my HWLayer.m aswell and where I use it in my code, is here:

Bomb *bombe = [[Bomb alloc] init];
bombe.position = explosionPoint;
bombe.length = player.explosionLength; //player is another CCSprite class. This one is from the method. ....fromPlayer:(PlayerSprite *)player
//Logging here works, tested and the bombe.position is valid and .length is valid 
[currentBombs addObject:bombe];
NSLog(@"%@",currentBombs); //Here doesn't, guessing crash is at ^

As said, it crashes on the addObject:line. I can't really see why, as I just replaced a not-classed CCSprite with a Bombclass. The crash is just a (lldb) and the thing on the left outputs a few thousand of these:

enter image description here

Which says description, so I would assume its in my CCSprite subclass the error is. BUT the bombe.* logging worked fine!

Does anyone understand why it doesn't work?

Edit:

enter image description here


Solution

  • EDIT:

    NSLog(@"%@",currentBombs); //Here doesn't, guessing crash is at ^
    

    Your %@ implies NSString. currentBombs is likely an int. Try

    NSLog(@"%i",currentBombs); //Here doesn't, guessing crash is at ^
    

    CCSprite requires a texture. You can (maybe?) have a CCSprite without one, but that's not what CCSprite is for.

    You will want to use CCNode for this purpose:

    CCNode* node = [CCNode new];
    

    This is a full-fledged Cocos2d object that you can move, etc. You'd add your Bomb to it, and move the CCNode around, like this:

    Bomb *myBomb = [Bomb new]; //or whatever
    CCNode* bombNode = [CCNode new];
    
    //add the bomb to the node
    [bombNode addChild:myBomb];
    
    //move the node
    bombNode.position = CGPointMake(10, 20)
    

    This allows you to remove the myBomb from your node, effectively having something that you can add whatever you want without needing to display anything, but when you want to, it can be done easily.

    Good luck