如何dynamic创build一个带有循环的2d NSMutableArray

我在这里做了一个原创的职位

起初,我试图填补CGPoint ** allPaths。

第一个维度是“path”,第二个维度是“路途点”。 我从这里得到一个CGPoint。

例如:allPaths [0] [2]会给我第一个path,第三个航点的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中的所有path都等于最后一个。 (所有的第一条path都被最后一条path覆盖)

我知道这是因为这一行[allPaths addObject:allWaypointsForAPath]。

但是,我该怎么做呢?

哦,我想我find了一些东西! 不知道内存问题,但我想垃圾回收器应该工作?

其实,我只需要在这个循环中声明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++; }