NSMutableArray of ClLocationCoordinate2D

前端 未结 5 925
遇见更好的自我
遇见更好的自我 2020-12-16 11:27

I\'m trying to create then retrieve an array of CLLocationCoordinate2D objects, but for some reason the array is always empty.

I have:

NSMutableArray         


        
相关标签:
5条回答
  • 2020-12-16 12:08

    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]];
    
    0 讨论(0)
  • 2020-12-16 12:18

    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.

    0 讨论(0)
  • 2020-12-16 12:22

    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];
    
    0 讨论(0)
  • 2020-12-16 12:22

    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!

    0 讨论(0)
  • 2020-12-16 12:27

    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];
    
    0 讨论(0)
提交回复
热议问题