using CLLocation objects as keys in dictionary

我是研究僧i 提交于 2019-12-07 03:16:48

问题


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.


回答1:


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.




回答2:


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



回答3:


It is totally permitted to use CLLocation as keys for a dictionary, no problem with that. The reason why you get nil is because no value is associated with the key, check where you fill the dictionary.

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



来源:https://stackoverflow.com/questions/6771508/using-cllocation-objects-as-keys-in-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!