一個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]。
然而,我該怎麼做呢?
如果您正在使用「objectNamed」和內部索引爲陣,爲什麼不直接切換到一個NSMutableDictionary? – Stavash 2012-07-28 06:44:40
其實,我想保留NSMutableArray,因爲我使用的索引號不是與鍵 – Kalzem 2012-07-28 07:03:35