Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing CLLocationCoordinates2D in NSMutableArray

After some searching, I got the following solution : reference.

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);

And access it as:

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

However, someone claims that there is a memory leak here? Can anyone suggest me where is the leak and how to fix it. Further, is there a better way of storing a list of CLLocationCoordinate2D in NSMutableArray? Please give sample code since I am an Objective C newbie.

like image 621
Amarsh Avatar asked Apr 05 '10 07:04

Amarsh


3 Answers

Here’s another way, using the builtin type NSValue which is made for exactly this purpose:

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

To retrieve the value use the following code:

CLLocationCoordinate2D old_coordinate;
[[points objectAtIndex:0] getValue:&old_coordinate];
like image 81
Nikolai Ruhe Avatar answered Sep 25 '22 14:09

Nikolai Ruhe


Starting with iOS 6, there's the NSValueMapKitGeometryExtensions for NSValue:

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

And to retrieve the value:

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

The NSValueMapKitGeometryExtensions require MapKit.framework
CLLocationCoordinate2DMake() requires CoreLocation.framework, so these imports are required:

#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
like image 37
Andreas Ley Avatar answered Sep 23 '22 14:09

Andreas Ley


There's no leak, just a waste of heap memory.

You could just use

CLLocationCoordinate2D new_coordinate;
new_coordinate.latitude = latitude;
new_coordinate.longitude = longitude;
[points addObject:[NSData dataWithBytes:&new_coordinate length:sizeof(new_coordinate)]];
like image 6
kennytm Avatar answered Sep 24 '22 14:09

kennytm