问题描述
是否可以将CLLocation对象用作字典中的键?当我尝试这个时,[dictionary objectForKey:clLocationObj]总是返回nil,即使已经插入了具有完全相同纬度和经度的CLLocation键。我能做错什么?
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.
推荐答案
CLLocation
似乎没有覆盖 isEqual
执行实际内容比较,而是根据对象标识比较相等性。因此,将 用作词典中的键是非常明智的,除非您始终使用完全相同的对象访问它。
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:
这篇关于使用CLLocation对象作为字典中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!