2010-08-12 19 views
8

我需要使用類似下面建立一個數組:CLLocationCoordinate2D不知道數組中會有多少?

CLLocationCoordinate2D points[4]; 


    points[0] = CLLocationCoordinate2DMake(41.000512, -109.050116); 

    points[1] = CLLocationCoordinate2DMake(41.002371, -102.052066); 

    points[2] = CLLocationCoordinate2DMake(36.993076, -102.041981); 

    points[3] = CLLocationCoordinate2DMake(36.99892, -109.045267); 

問題是,我永遠不會知道有多少項目會如何是數組中,這樣我就可以指定計數。有沒有辦法創建一個CLLocationCoordinate2D數組,只需插入新的座標而不知道最終總數是多少?

編輯:我最終的目標是使用座標來製作MKPolyline,使用polylineWithCoordinates方法,它需要一個CLLocationCoordinate2D數組。

回答

15
// unpacking an array of NSValues into memory 
CLLocationCoordinate2D *points = malloc([mutablePoints count] * sizeof(CLLocationCoordinate2D)); 
for(int i = 0; i < [mutablePoints count]; i++) { 
    [[mutablePoints objectAtIndex:i] getValue:(points + i)]; 
} 

MKPolyline *myPolyline = [MKPolyline polylineWithCoordinates:points count:[mutablePoints count]]; 
free(points); 
+0

不要忘記在該.m文件中添加#include AND,函數是sizeof(...)而不是size_of(...) ...剛剛爲你保存了15分鐘。 :D否則工作很好! – horseshoe7 2011-07-21 08:29:39

+0

這裏實際發生了什麼: CLLocationCoordinate2D * points = malloc([mutablePoints count] * sizeof(CLLocationCoordinate2D)); 如果有人能指出這一點,那將會很棒。我們不是創建一個C數組不是我們? – onigunn 2013-02-20 20:42:12

+1

我們的確在創建一個C數組。請參閱polylineWithCoordinates的文檔:count :. – 2013-02-21 00:31:12

1

將它們放在NSValue物體中,並將​​它們扔入NSMutableArray

+0

但我想從這使用polylineWithCoordinates方法創建一個MKPolyline。 – 2010-08-12 21:24:10

+0

你必須從你的NSMutableArray中解壓縮它們,然後用一些指針數學運算到內存中。 – 2010-08-12 22:25:21

相關問題