0

我在这里发了一篇原创文章

起初,我尝试填写一个 CGPoint **allPaths。

第一个维度是“路径”,第二个维度是“路点”。我从中得到了一个 CGPoint。

例如: allPaths[0][2] 会给我第一条路径的 CGPoint,第三个航路点。

我用普通的 C 语言成功地用讨厌的循环做到了。现在我正在尝试使用 NSMutableArrays 在 Obj-C 中做同样的事情。

这是我的代码:

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]。

然而,我该怎么做呢?

4

1 回答 1

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++;
}
于 2012-07-28T07:14:07.780 回答