Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using CLLocation objects as keys in dictionary

Is it possible to use CLLocation objects as keys in a dictionary? When I try this, the [dictionary objectForKey: clLocationObj] always returns nil even when there are CLLocation keys already inserted with exactly the same latitude and longitude. What could I be doing wrong?

       for (Location *location in someArray) {
               CLLocation *locationKey = [[CLLocation alloc] initWithLatitude:[location.latitude doubleValue] longitude:[location.longtitude doubleValue]];
               LocationAnnotation *annotationAtLocation = [self.uniqueLocations objectForKey:locationKey];
               if (annotationAtLocation == nil)
                    NSLog(@"this is always nil");
       }

I know from my debugging that there are multiple objects of Location with the same latitude and longitude in someArray.

like image 368
Z S Avatar asked Jul 21 '11 05:07

Z S


2 Answers

CLLocation does not seem to override isEqual to perform actual content comparison, instead it compares the equality based on object identity. Therefore it is not wise to use it as a key in a dictionary, unless you are always accessing it using the exact same object.

The solution you have described in a comment is quite good workaround for many situations:

I ended up converting the CLLocationCoordinate2D object into an NSValue and used that as the key to the dictionary.

like image 86
Palimondo Avatar answered Nov 19 '22 14:11

Palimondo


There is NSValueMapKitGeometryExtensions category on NSValue in MapKit framework

//to set
NSValue *locationValue = [NSValue valueWithMKCoordinate:location.coordinate];
[dictionary setObject:object forKey:locationValue];

//to get
NSValue *coordinateValue = dictionary[locationValue];
CLLocationCoordinate2D coordinate = [coordinateValue MKCoordinateValue];
like image 6
beryllium Avatar answered Nov 19 '22 14:11

beryllium