Reputation: 398
I'm trying to create then retrieve an array of CLLocationCoordinate2D objects, but for some reason the array is always empty.
I have:
NSMutableArray *currentlyDisplayedTowers;
CLLocationCoordinate2D new_coordinate = { currentTowerLocation.latitude, currentTowerLocation.longitude };
[currentlyDisplayedTowers addObject:[NSData dataWithBytes:&new_coordinate length:sizeof(new_coordinate)] ];
I've also tried this for adding the data:
[currentlyDisplayedTowers addObject:[NSValue value:&new_coordinate withObjCType:@encode(struct CLLocationCoordinate2D)] ];
And either way, the [currentlyDisplayedTowers count] always returns zero. Any ideas what might be going wrong?
Thanks!
Upvotes: 21
Views: 18829
Reputation: 2228
For anyone else with this issue, there's another solution if you are planning on using MapKit
.
(The reason I say IF, of course, is because importing a module such as MapKit
purely for a convenient wrapper method is probably not the best move.. but nonetheless here you go.)
@import MapKit;
Then just use MapKit's coordinate value wrapper whenever you need to:
[coordinateArray addObject:[NSValue valueWithMKCoordinate:coordinateToAdd]];
In your example..
[currentlyDisplayedTowers addObject:[NSValue valueWithMKCoordinate:new_coordinate]];
Upvotes: 0
Reputation: 398
I had currentlyDisplayedTowers = nil
which was causing all the problems. Also, the previous advice to init and alloc were necessary. Thanks everyone for the help!
Upvotes: 1
Reputation: 141879
To stay in object land, you could create instances of CLLocation
and add those to the mutable array.
CLLocation *towerLocation = [[CLLocation alloc] initWithLatitude:lat longitude:lon];
[currentDisplayedTowers addObject:towerLocation];
To get the CLLocationCoordinate
struct back from CLLocation
, call coordinate
on the object.
CLLocationCoordinate2D coord = [[currentDisplayedTowers lastObject] coordinate];
Upvotes: 50
Reputation: 1290
As SB said, make sure your array is allocated and initialized.
You’ll also probably want to use NSValue
wrapping as in your second code snippet. Then decoding is as simple as:
NSValue *wrappedCoordinates = [currentlyDisplayedTowers lastObject]; // or whatever object you wish to grab
CLLocationCoordinate2D coordinates;
[wrappedCoordinates getValue:&coordinates];
Upvotes: 3
Reputation: 22904
You need to allocate your array.
NSMutableArray* currentlyDisplayedTowers = [[NSMutableArray alloc] init];
Then you can use it. Be sure to call release when you are done with it or use another factory method.
Upvotes: 1