views:

211

answers:

2

After some searching, I got the following solution : ref: http://stackoverflow.com/questions/1392909/nsmutablearray-addobject-with-mallocd-struct

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.

A: 

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)]];
KennyTM
+4  A: 

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(struct CLLocationCoordinate2D)]];

To retrieve the value use the following code:

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