2013-03-05 90 views
0

我一直試圖讓我的數組數,但它一直返回0,我認爲它沒有正確添加對象。我將我的屬性放在頭文件中並將其合成到layer.m文件中。我在我的超級初始化中分配了空間。NSMutableArray不添加對象

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]); 
      } 

     } 
    } 
} 
+0

請先檢查此代碼是否通過了if語句。 'tileGid1 == 1'可能永遠不會計算爲TRUE(是)。我假設你已經將定義和啓動分開了! – ipinak 2013-03-05 01:06:24

+0

[無法添加對象到NSMutableArray]的可能的重複(http://stackoverflow.com/q/851926)[無法添加項目到NSMutableArray ivar](http://stackoverflow.com/q/7125326),[\ [NSMutableArray addObject:\]不影響計數](http://stackoverflow.com/q/3683761),[\ [NSMutableArray addObject:\] not working](http://stackoverflow.com/q/1827058) – 2013-03-05 01:46:21

回答

2

無論採用哪種方式你在初始化asteroids既可以當findTiles是或根本不運行不運行。沒有更多的信息,就不可能說更多,但這幾乎可以肯定發生了什麼。

+0

Bingo ,謝謝,菜鳥的錯誤。 – user2121776 2013-03-05 01:17:54

1

當你初始化你叫self.asteroids = [[NSMutableArray alloc] init];,但是當你加入你呼叫[asteroids addObject:tileonPos[amounts]];

嘗試:[self.asteroids addObject:tileonPos[amounts]];[_asteroids addObject:tileonPos[amounts]];

也是你確定self.asteroids = [[NSMutableArray alloc] init];在初始化執行?

0

如果您只是要將對象添加到findTiles方法中的「小行星」,請嘗試在for循環前初始化該方法中的數組。

self.asteroids = [@[] mutableCopy];