使用CLLocation对象作为字典中的键 [英] using CLLocation objects as keys in dictionary

查看:76
本文介绍了使用CLLocation对象作为字典中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将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:


我最终转换了 CLLocationCoordinate2D 将对象转换为 NSValue 并使用
作为字典的关键字。

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

这篇关于使用CLLocation对象作为字典中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆