问题
I made an original post here
At first, I tried to fill up a CGPoint **allPaths.
With the first dimension being "a path" and the second dimension being "the waypoint". And I get a CGPoint out of this.
For example : allPaths[0][2] would give me the CGPoint of the first path, third waypoint.
I successfully did it in plain C with nasty loops. And now I am trying to do the same thing in Obj-C with NSMutableArrays.
Here is my code :
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++;
}
My actual problem is that all paths in allPaths are equal to the last one. (all the first paths are overrided with the last one)
I know that it is because of this line [allPaths addObject:allWaypointsForAPath].
Yet, how should I do it ?
回答1:
Oh I think I found out something ! Not sure about memory issue, but I guess the garbage collector should work ?
Actually, I just have to declaremy NSMutableArray *allWaypointsForAPath in the loop like this :
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++;
}
来源:https://stackoverflow.com/questions/11698682/how-to-dynamically-create-a-2d-nsmutablearray-with-loops