简体   繁体   English

在Objective-C中对多维数组进行排序

[英]Sorting a multidimensional array in objective-c

I'm trying to sort a multidimensional array in objective-c i know that i can sort a single dimensional array using the line of code below: 我正在尝试在Objective-C中对多维数组进行排序,我知道我可以使用以下代码行对一维数组进行排序:

NSArray *sortedArray = [someArray sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

I can't seem to figure out how to sort a 2D array like the one below: 我似乎无法弄清楚如何对2D数组进行排序,如下所示:

 ( ("SOME_URL", "SOME_STORY_TITLE", "SOME_CATEGORY"),
    ("SOME_URL", "SOME_STORY_TITLE", "SOME_CATEGORY"),
    ("SOME_URL", "SOME_STORY_TITLE", "SOME_CATEGORY") );

If someone could provide me code that would sort the array by SOME_CATEGORY it would be of great help to me. 如果有人可以向我提供按SOME_CATEGORY对数组进行排序的代码,那对我会很有帮助。

Thanks, 谢谢,

Zen_Silence Zen_Silence

You need to use -sortedArrayUsingFunction:context: or sortedArrayUsingFunction:context:hint: . 您需要使用-sortedArrayUsingFunction:context:sortedArrayUsingFunction:context:hint:

static NSInteger order (id a, id b, void* context) {
    NSString* catA = [a lastObject];
    NSString* catB = [b lastObject];
    return [catA caseInsensitiveCompare:catB];
}
...
NSArray* sortedArray = [someArray sortedArrayUsingFunction:order context:NULL];

Alternatively, create a custom class for your inner "array" (which is more like a record), and implement a -compareByCategory: method on it. 另外,为您的内部“数组”(更像是一条记录)创建一个自定义类,并在其上实现-compareByCategory:方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM