0

I keep trying to get my array count but it keeps returning 0, i think its not adding the object correctly. I Put my property in header file and synthesized it in the layer.m file. i allocated space in my super init.

NSMutableArray *asteroids;

@property (strong) NSMutableArray *asteroids;

@synthesize asteroids;

self.asteroids = [[NSMutableArray alloc] init];

-(void)findTiles
{
    CGPoint tilecoord1;
    int tileGid1;
    int aheadcount = 200;
    CCSprite *tileonPos[aheadcount];
    int amounts = 0;

    for(int x = 0; x<30; x++)
    {
        for(int y = 0; y<20; y++)
        {
            tilecoord1 = ccp(x+(480*currentlevel),y);
            tileGid1 = [bglayer tileGIDAt:tilecoord1];
            if(tileGid1 == 1)
            {
                tileonPos[amounts] = [bglayer tileAt:ccp(x,y)];
                amounts++;
                [asteroids addObject:tileonPos[amounts]];
                NSLog(@"%d",[asteroids count]);
            }

        }
    }
}
Sebastian
  • 7,670
  • 5
  • 38
  • 50
user2121776
  • 123
  • 9
  • Check first if this code passes the if statement. `tileGid1 == 1` might never evaluate to TRUE (YES). I assume that you have separated the definition and the initiation! – ipinak Mar 05 '13 at 01:06
  • possible duplicate of [Having trouble adding objects to NSMutableArray](http://stackoverflow.com/q/851926) [Cannot add items to an NSMutableArray ivar](http://stackoverflow.com/q/7125326), [\[NSMutableArray addObject:\] not affecting count](http://stackoverflow.com/q/3683761), [\[NSMutableArray addObject:\] not working](http://stackoverflow.com/q/1827058) – jscs Mar 05 '13 at 01:46

3 Answers3

2

Whatever method you're initializing asteroids in either isn't run when findTiles is or isn't run at all. Without more information, it's impossible to say more, but that's almost certainly what's going on.

Chuck
  • 234,037
  • 30
  • 302
  • 389
1

when you init you called self.asteroids = [[NSMutableArray alloc] init]; but when you adding you call [asteroids addObject:tileonPos[amounts]];.

try: [self.asteroids addObject:tileonPos[amounts]]; or [_asteroids addObject:tileonPos[amounts]];

also are you sure the self.asteroids = [[NSMutableArray alloc] init]; is executed in init?

Sebastian
  • 7,670
  • 5
  • 38
  • 50
Ikmal Ezzani
  • 1,283
  • 8
  • 13
0

If you are only going to add objects to "asteroids" in findTiles method, try initializing the array in that method before for loop .

self.asteroids = [@[] mutableCopy];
Anupdas
  • 10,211
  • 2
  • 35
  • 60