Using CLLocation Objects as Keys in a Dictionary

Can CLLocation objects be used as keys in a dictionary? When I try to do this, [dictionary objectForKey: clLocationObj] always returns zero even when there are CLLocation keys already inserted with exactly the same latitude and longitude. What can i do 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"); } 

From my debugging, I know that someArray has several Location objects with the same latitude and longitude.

+6
source share
3 answers

CLLocation does not isEqual to override isEqual to actually match the content, instead it compares equality based on the identifier of the object. Therefore, it is not wise to use it as a key in a dictionary if you do not always access it using the same object.

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

I finished converting the CLLocationCoordinate2D object to NSValue and used that as the key to the dictionary.

+6
source

In the MapKit structure, there is an NSValueMapKitGeometryExtensions category NSValue

 //to set NSValue *locationValue = [NSValue valueWithMKCoordinate:location.coordinate]; [dictionary setObject:object forKey:locationValue]; //to get NSValue *coordinateValue = dictionary[locationValue]; CLLocationCoordinate2D coordinate = [coordinateValue MKCoordinateValue]; 
+5
source

It is fully allowed to use CLLocation as keys for a dictionary, no problem. The reason you get nil is because no value is associated with the key, check where you populate the dictionary.

About your multiple CLLocation keys, every time you set an object for a key that already exists in the dictionary, the previous value will be sent to the release message, and the new one will take its place. Therefore, if you have several storage locations, and some are equal, you should find another type as the key for the dictionary.

+2
source

Source: https://habr.com/ru/post/893228/


All Articles