cocoa - 按数组中包含的 int 对 NSArray 进行排序

标签 cocoa sorting nsarray int

我有一个数组,我们称之为“数组”,在数组内部我有这样的对象:

“0这是一个对象”

“4 这是另一个对象”

“2 我们也在这里放 2!”

“1 到底是什么,这是另一个!”

“3 让我们把这个放在这里”

我想按该数字对数组进行排序,所以它会变成这样:

“0这是一个对象”

“1 到底是什么,这是另一个!”

“2 我们也在这里放 2!”

“3 让我们把这个放在这里”

“4 这是另一个对象”

最佳答案

您可以使用NSArray的 sortedArrayUsingFunction:Context:方法为您对这些进行排序。此方法采用一个可用于比较数组中的两个项目的函数。

#import <Foundation/Foundation.h>

NSInteger firstNumSort(id str1, id str2, void *context) {
    int num1 = [str1 integerValue];
    int num2 = [str2 integerValue];

    if (num1 < num2)
        return NSOrderedAscending;
    else if (num1 > num2)
        return NSOrderedDescending;

    return NSOrderedSame;
}

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSArray *array = [NSArray arrayWithObjects:@"0 Here is an object",
                      @"4 Here's another object",
                      @"25 Let's put 2 here too!",
                      @"1 What the heck, here's another!",
                      @"3 Let's put this one right here",
                      nil];

    NSLog(@"Sorted: %@", [array sortedArrayUsingFunction:firstNumSort context:NULL]);

    [pool drain];
    return 0;
}

关于cocoa - 按数组中包含的 int 对 NSArray 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1870656/

相关文章:

sorting - 如何在 clojure 中根据另一个向量的值对一个向量进行排序

c# - 在列表中查找不同的匹配项

objective-c - 比较不同 NSObject 子类的 3 个数组

ios - 从字典中提取值的神奇方法

iphone - 逐步通过 plist 获取信息

iphone - Core Data 存在于 iPhone 上吗?或者您将如何在 iPhone 上保存数据?

cocoa - NSArray 中对象的最大数量

c++ - 是否可以使用 std::sort 按词典顺序排序?

objective-c - 已弃用 : Rounded Textured Segmented Control

cocoa - 如何在注意力不集中时使 TouchBar 保持事件状态