通过数组中包含的int对NSArray进行排序 [英] Sort NSArray's by an int contained in the array

查看:111
本文介绍了通过数组中包含的int对NSArray进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an array, let's call it "array" and inside of the array I have objects like this:

0这是一个对象

4这是另一个对象

2我们也把2放在这里!

"2 Let's put 2 here too!"

1哎呀,这是另一个!

3我们把这个放在这里

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

I would like to sort the arrays by that number, so it'll turn into this:

0这是一个对象

1哎呀,这是另一个!

2我们也把2放在这里!

"2 Let's put 2 here too!"

3我们把这个放在这里

4这是另一个对象

推荐答案

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

You can use NSArray's sortedArrayUsingFunction:Context: method to sort these for you. This method takes a function that can be used to compare two items in the array.

#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;
}

这篇关于通过数组中包含的int对NSArray进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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