OBJ / C:排序自定义顺序的数组 [英] Obj/C: Sorting an array on a custom order

查看:277
本文介绍了OBJ / C:排序自定义顺序的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有NSMutableDictionaries阵列,包含(其中包括)的关键位置。
我需要数组输入其分类到一个表中。在上面应该是N,下面应该是A,而低于应R.
因此,在排序:我如何排序的顺序一个数组:N - 一 - R的

I've got an array of NSMutableDictionaries, containing (amongst others) the key Location. I need to sort the array to input it into a table. On top should be N, below should be A, and below that should be R. So in sort: How can I sort an array in the order: N - A - R?

编辑:我可以通过看两个变量命令,但我使用超过2变量(共7)...

I can order by looking at two variables, but I'm using more then 2 variables (7 in total)...

谢谢,

推荐答案

如果您的数组是可变的,你可以使用-sortUsing ...方法排序。如果没有,你可以使用-sortedArrayUsing ...方法创建一个新的,排序的数组。例如,有-sortUsingComparator:和-sortedArrayUsingComparator:其中取比较器块作为一个参数的方法。你只需要提供用于比较使用自定义排序次序两个对象,这样一个块:

If your array is mutable, you can sort it using the -sortUsing... methods. If not, you can create a new, sorted array using the -sortedArrayUsing... methods. For example, there are -sortUsingComparator: and -sortedArrayUsingComparator: methods which take a comparator block as a parameter. You just need to supply a block that compares two objects using your custom sort order, like this:

[myArray sortUsingComparator:^(id firstObject, id secondObject) {
    NSString *firstKey = [firstObject valueForKey:@"location"];
    NSString *secondKey = [secondObject valueForKey:@"location"];
    if ([firstKey stringEqual:@"N"] || [lastKey stringEqual:@"R"])
        return NSOrderedAscending;
    else if ([firstKey stringEqual:secondKey])
        return NSOrderedSame;
    else
        return NSOrderedDescending;
}];

有数组排序的pretty深入的讨论,结合实例,在<一个href=\"http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Collections/Articles/Arrays.html#//apple_ref/doc/uid/20000132-SW5\">Collections编程主题文件。

这篇关于OBJ / C:排序自定义顺序的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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