如何对数组进行排序

发布于 2024-09-01 19:03:27 字数 474 浏览 4 评论 0原文

我的应用程序中有一个数组,我需要按其键之一进行排序。

基本上,该应用程序的作用是在某处获取纬度和经度,计算距我的实际位置的距离,并创建一个包含名为“距离”的键的数组。

我正在使用

myArray sortUsingDescriptors:
    [NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"distance" ascending:YES] autorelease]]];

我不确定它是否有效,我的意思是第一个结果已排序,但随后它显示与前一个结果更接近的距离,例如:

0.8 km
1.6 km
1.9 km
10053.9 km
1098.0 km
2372.0 km
470.5 km

有什么建议吗?

我预先感谢您提供的任何帮助。

法布里奇奥

I got an array in my app and I need to order by one of its key.

Basically what the app does is taking latitude and longitude somewhere, calculate the distance from my actual position and create an array containing a key called "distance".

I'm using

myArray sortUsingDescriptors:
    [NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"distance" ascending:YES] autorelease]]];

I'm not sure it's working, I mean the first results are ordered but then it shows distance closer to the previous, as example:

0.8 km
1.6 km
1.9 km
10053.9 km
1098.0 km
2372.0 km
470.5 km

Any suggestion?

I thank you in advance for any kind of help.

Fabrizio

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月隐月明月朦胧 2024-09-08 19:03:27

如果您的距离值是字符串,这看起来像是一个有效的排序。要获得数字排序,您应该将其保存为 NSNumber。

That looks like a valid ordering - if your distance value is a string. To get a numeric ordering you should save it as a NSNumber.

海未深 2024-09-08 19:03:27

您应该能够使用尊重数值的自定义排序函数。

(我现在假设您的对象的“距离”键是一个 NSString

static NSInteger numericCompare(id first, id second, void* context)
{
    return [(NSString*)[first distance] compare:[second distance] options:NSCaseInsensitiveSearch | NSNumericSearch];
}

现在您可以使用 NSArray 中的排序方法获取已排序的数组

NSArray* sortedArray = [myArray sortedArrayUsingFunction:numericCompare context:NULL];

You should be able to use a custom sorting function that respects numerical values.

(I'm now assuming the "distance" key of your objects is a NSString

static NSInteger numericCompare(id first, id second, void* context)
{
    return [(NSString*)[first distance] compare:[second distance] options:NSCaseInsensitiveSearch | NSNumericSearch];
}

Now you can get your sorted array using the sort method in NSArray

NSArray* sortedArray = [myArray sortedArrayUsingFunction:numericCompare context:NULL];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文