如何动态创建带循环的2d NSMutableArray

时间:2012-07-28 05:56:08

标签: ios cocos2d-iphone 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]。

然而,我应该怎么做?

1 个答案:

答案 0 :(得分:0)

哦,我觉得我发现了什么! 不确定内存问题,但我想垃圾收集器应该可以工作吗?

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