典型的解决方案是创建一个NSObject
子类并定义一个属性 a CLLOcationCoordinate2D
。实例化这些对象并将其添加到您的数组中。
@interface Coordinate : NSObject
@property (nonatomic) CLLocationCoordinate2D coordinate;
- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate;
@end
@implementation Coordinate
- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate
{
self = [super init];
if (self) {
_coordinate = coordinate;
}
return self;
}
@end
然后,因为 yourlocationArray
是一个数组MKUserLocation
(它本身符合MKAnnotation
),你可以这样做:
NSMutableArray *path;
path = [NSMutableArray array];
for (id<MKAnnotation> annotation in locationArray)
{
// determine latitude and longitude
[path addObject:[[Coordinate alloc] initWithCoordinate:annotation.coordinate]];
}
或者制作一个现有对象类型的数组,例如CLLocation
orMKPinAnnotation
或其他。
或者,如果此数组是要在地图上绘制的路径,您可能希望避免使用自己的数组,而是制作一个MKPolyline
.
NSInteger pathLength = [locationArray count];
CLLocationCoordinate2D polylineCoordinates[pathLength]; // note, no malloc/free needed
for (NSInteger i = 0; i < pathLength; i++)
{
id<MKAnnotation> annotation = locationArray[i];
polylineCoordinates[i] = annotation.coordinate;
}
MKPolyline *polyline = [MKPolyline polylineWithCoordinates:polylineCoordinates count:pathLength]
[self.mapView addOverlay:polyline];
这取决于这样做的目的是什么。但是,如果您可以使用避免malloc
and的先前构造之一free
,那可能是理想的。这些技术利用了 Objective-C 模式,使其更难泄漏、使用无效指针等。