NSSortDescriptor 用于比较 Cocoa/iPhone 中的 CLLocation 对象
我有一个 CLLocation 对象数组,我希望能够比较它们以获取与起始 CLLocation 对象的距离。 数学很简单,但我很好奇是否有一个方便的排序描述符来执行此操作? 我应该避免 NSSortDescriptor 并编写自定义比较方法 + 冒泡排序吗? 我通常最多比较 20 个对象,因此不需要非常高效。
I have an array of CLLocation objects and I'd like to be able to compare them to get distance from a starting CLLocation object. The math is straight forward but I'm curious if there is a convenience sort descriptor to go about doing this? Should I avoid NSSortDescriptor and write a custom compare method + bubble sort? I'm usually comparing at most 20 objects, so it doesn't need to be super efficient.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以为 CLLocation 编写一个简单的compareToLocation:类别,根据自身与其他 CLLocation 对象之间的距离返回 NSOrderedAscending、NSOrderedDescending 或 NSOrderedSame。 然后简单地做这样的事情:
编辑:
像这样:
You can write a simple compareToLocation: category for CLLocation that returns either NSOrderedAscending, NSOrderedDescending, or NSOrderedSame depending on the distances between self and the other CLLocation object. Then simply do something like this:
Edit:
Like this:
为了改进 Dave 的答案...
从 iOS 4 开始,您可以使用比较器块并避免使用静态变量和类别:
To improve on Dave's answer...
As of iOS 4, you can use a comparator block and avoid having to use a static variable and category:
只是为了添加到类别响应(这是要走的路),不要忘记您实际上不需要自己做任何数学运算,您可以使用 CLLocation 实例方法:
获取两个位置对象之间的距离。
Just to add to the category response (which is the way to go), don't forget you don't actually need to do any math yourself, you can use the CLLocation instance method:
To get the distance between two location objects.