简体   繁体   中英

NSMutableArray of ClLocationCoordinate2D

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!

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

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

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.

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM