2012-07-28 80 views
0

一個2D的NSMutableArray我製作的原創帖子here如何動態地創建循環

起初,我試圖填補一個CGPoint ** allPaths。

第一個維度是「一條路徑」,第二個維度是「航點」。我從中得到一個CGPoint。

例如:allPaths [0] [2]會給我第一個路徑,第三個航點的CGPoint。

我成功地用簡單的C做了令人討厭的循環。現在我正試圖在Obj-C和NSMutableArrays中做同樣的事情。

這裏是我的代碼:

CCTMXObjectGroup *path; 
NSMutableDictionary *waypoint; 

int pathCounter = 0; 
int waypointCounter = 0; 

NSMutableArray *allPaths = [[NSMutableArray alloc] init]; 
NSMutableArray *allWaypointsForAPath = [[NSMutableArray alloc] init]; 

//Get all the Paths 
while ((path = [self.tileMap objectGroupNamed:[NSString stringWithFormat:@"Path%d", pathCounter]])) 
{ 
    waypointCounter = 0; 
    //Empty all the data of the waypoints (so I can reuse it) 
    [allWaypointsForAPath removeAllObjects]; 

    //Get all the waypoints from the path 
    while ((waypoint = [path objectNamed:[NSString stringWithFormat:@"Wpt%d", waypointCounter]])) 
    { 
     int x = [[waypoint valueForKey:@"x"] intValue]; 
     int y = [[waypoint valueForKey:@"y"] intValue]; 

     [allWaypointsForAPath addObject:[NSValue valueWithCGPoint:CGPointMake(x, y)]]; 
     //Get to the next waypoint 
     waypointCounter++; 
    } 

    //Add the waypoints of the path to the list of paths 
    [allPaths addObject:allWaypointsForAPath]; 

    //Get to the next path 
    pathCounter++; 
} 

我實際的問題是,在allPaths所有路徑都等於最後一個。 (所有的第一個路徑被最後一個覆蓋)

我知道這是因爲這一行[allPaths addObject:allWaypointsForAPath]。

然而,我該怎麼做呢?

+0

如果您正在使用「objectNamed」和內部索引爲陣,爲什麼不直接切換到一個NSMutableDictionary? – Stavash 2012-07-28 06:44:40

+0

其實,我想保留NSMutableArray,因爲我使用的索引號不是與鍵 – Kalzem 2012-07-28 07:03:35

回答

0

哦,我想我找到了一些東西! 不確定內存問題,但我猜垃圾回收器應該工作?

其實,我只是declaremy的NSMutableArray * allWaypointsForAPath在這樣的循環:

int pathCounter = 0; 
int waypointCounter = 0; 

NSMutableArray *allPaths = [[NSMutableArray alloc] init]; 

//Get all the PathZ 
while ((path = [self.tileMap objectGroupNamed:[NSString stringWithFormat:@"Path%d", pathCounter]])) 
{ 
    waypointCounter = 0; 
    NSMutableArray *allWaypointsForAPath = [[NSMutableArray alloc] init]; 
    //Get all the waypoints from the path 
    while ((waypoint = [path objectNamed:[NSString stringWithFormat:@"Wpt%d", waypointCounter]])) 
    { 
     int x = [[waypoint valueForKey:@"x"] intValue]; 
     int y = [[waypoint valueForKey:@"y"] intValue]; 
     [allWaypointsForAPath addObject:[NSValue valueWithCGPoint:CGPointMake(x, y)]]; 
     //Get to the next waypoint 
     waypointCounter++; 
    } 

    [allPaths addObject:allWaypointsForAPath]; 
    //Get to the next path 
    pathCounter++; 
} 
+1

是的,你明白爲什麼嗎?因爲在你的原始代碼中,你只是重複使用相同的數組[即相同的指針](很明顯,你所有的實例最終都會指向內存中的相同位置^^)。這段代碼每次都會創建一個新的指針。請注意您的條款,因爲iOS上沒有垃圾回收。 ARC應該完成它的工作(我認爲它已啓用?)並釋放任何未使用的對象。 – borrrden 2012-07-28 15:59:57

+0

是的,我現在明白了。我已經啓用ARC,我希望它能夠正確釋放內存! =)(我想我會重新發佈一個問題,如果我得到內存問題) – Kalzem 2012-07-28 16:53:01