将CLLocationCoordinates2D存储在NSMutableArray中

15

经过一番搜索,我找到了以下解决方案:参考链接

CLLocationCoordinate2D* new_coordinate = malloc(sizeof(CLLocationCoordinate2D));
new_coordinate->latitude = latitude;
new_coordinate->longitude = longitude;
[points addObject:[NSData dataWithBytes:(void *)new_coordinate
length:sizeof(CLLocationCoordinate2D)]];
free(new_coordinate);

并且可以这样访问它:

CLLocationCoordinate2D* c = (CLLocationCoordinate2D*) [[points objectAtIndex:0] bytes];

但是,有人声称这里存在内存泄漏?有人能建议我泄漏在哪里以及如何修复它吗?此外,有没有更好的方法将CLLocationCoordinate2D列表存储在NSMutableArray中?由于我是Objective C新手,请提供示例代码。

3个回答

70

以下是另一种方法,使用内置类型NSValue,该类型正是为此目的而设计的:

CLLocationCoordinate2D new_coordinate = { latitude, longitude };
[points addObject:[NSValue valueWithBytes:&new_coordinate objCType:@encode(CLLocationCoordinate2D)]];

使用以下代码来获取值:

CLLocationCoordinate2D old_coordinate;
[[points objectAtIndex:0] getValue:&old_coordinate];

1
NSValue是一个更好的选择,因为它专门针对此问题设计。此外,你应该摒弃结构体。 - Robert Childan
我创建了一个对象,其中包含两个双精度属性,用于保存纬度和经度。因为我需要添加NSCoding兼容性。 但是使用这个建议并没有成功,因为在持久化时它将其视为结构体,并且无法对结构体进行编码。 - LolaRun
@LolaRun 在SO上,跟进问题是不被赞同的。你应该将其作为一个单独的问题发布。 - Nikolai Ruhe
但我没有询问任何问题...我只是为那些想要将CLLocationCoordinate2D存储在数组中,并且"额外"希望持久化此数组的人添加了一条备注。仅此而已...谢谢 - LolaRun
@LolaRun 哦,我明白了,对于误解我很抱歉。 - Nikolai Ruhe
谢谢,这很有帮助。不过手动处理所有这些编组可能会有点麻烦。 - MattD

51

iOS 6 开始,NSValue 添加了 NSValueMapKitGeometryExtensions 扩展:

NSMutableArray *points = [NSMutableArray array];
CLLocationCoordinate2D new_coordinate = CLLocationCoordinate2DMake(latitude, longitude);
[points addObject:[NSValue valueWithMKCoordinate:new_coordinate]];

并且获取值:

CLLocationCoordinate2D coordinate = [[points objectAtIndex:0] MKCoordinateValue];

NSValueMapKitGeometryExtensions需要导入MapKit.frameworkCLLocationCoordinate2DMake()需要导入CoreLocation.framework,所以需要这些导入:

CLLocationCoordinate2DMake() 需要导入 CoreLocation.framework,因此需要进行这些导入操作:

#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

这应该是被接受的答案。 - Yaro

6

没有泄漏,只是堆内存的浪费。

你可以直接使用

CLLocationCoordinate2D new_coordinate;
new_coordinate.latitude = latitude;
new_coordinate.longitude = longitude;
[points addObject:[NSData dataWithBytes:&new_coordinate length:sizeof(new_coordinate)]];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接