如何使用比较:选项对 NSArray 进行排序

发布于 2024-08-18 00:12:33 字数 272 浏览 5 评论 0原文

我有一个 NSArray,其中包含数字作为 NSString 对象。 IE。

[array addObject:[NSString stringWithFormat:@"%d", 100]];

如何对数组进行数字排序?我可以使用 compare:options 并将 NSNumericSearch 指定为 NSStringCompareOptions 吗?请给我一个示例/示例代码。

I have an NSArray containing numbers as NSString objects. ie.

[array addObject:[NSString stringWithFormat:@"%d", 100]];

How do I sort the array numerically? Can I use compare:options and specify NSNumericSearch as NSStringCompareOptions? Please give me an example/sample code.

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

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

发布评论

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

评论(2

无风消散 2024-08-25 00:12:34

您可以使用为 sortedArrayUsingFunction:context: 方法也应该适用于 NSStrings,因为它们也有 intValue 方法。

// Place this functions somewhere above @implementation
static NSInteger intSort(id num1, id num2, void *context)
{
    int v1 = [num1 intValue];
    int v2 = [num2 intValue];
    if (v1 < v2)
        return NSOrderedAscending;
    else if (v1 > v2)
        return NSOrderedDescending;
    else
        return NSOrderedSame;
}

// And used like this
NSArray *sortedArray; 
sortedArray = [anArray sortedArrayUsingFunction:intSort context:NULL];

You can use the example code given for the sortedArrayUsingFunction:context: method which should work fine for NSStrings too as they also have the intValue method.

// Place this functions somewhere above @implementation
static NSInteger intSort(id num1, id num2, void *context)
{
    int v1 = [num1 intValue];
    int v2 = [num2 intValue];
    if (v1 < v2)
        return NSOrderedAscending;
    else if (v1 > v2)
        return NSOrderedDescending;
    else
        return NSOrderedSame;
}

// And used like this
NSArray *sortedArray; 
sortedArray = [anArray sortedArrayUsingFunction:intSort context:NULL];
病毒体 2024-08-25 00:12:34

由于您的对象是数字,因此您可以使用 NSNumber 对象(通过 stringValue 属性轻松转换为字符串),而不是使用 NSString 对象,并使用 sortedArrayUsingDescriptors:

例如:

NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES];
NSArray *sorters = [[NSArray alloc] initWithObjects:sorter, nil];
[sorter release];
NSArray *sortedArray = [anArray sortedArrayUsingDescriptors:sorters];
[sorters release];

Since your objects are numbers, instead of using NSString objects, you could use NSNumber objects (easily turned into strings via the stringValue property) and sort the array using sortedArrayUsingDescriptors:.

For example:

NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES];
NSArray *sorters = [[NSArray alloc] initWithObjects:sorter, nil];
[sorter release];
NSArray *sortedArray = [anArray sortedArrayUsingDescriptors:sorters];
[sorters release];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文