Objective-C,对多维数组进行排序 [英] Objective-C, sorting muti-dimensional arrays

查看:101
本文介绍了Objective-C,对多维数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中对多维数组进行排序时遇到了一些麻烦.我基本上有一个数组,其中每个元素都是以下形式的数组:

I've been having some trouble with sorting multi-dimensional arrays in Objective-C. I basically have an array of which every element is an array of the form:

(NSString, NSDate, NSString, NSString)

使我的顶级数组具有以下形式:

such that my top level array has the form:

(
(NSString, NSDate, NSString, NSString),
(NSString, NSDate, NSString, NSString),
(NSString, NSDate, NSString, NSString),
(NSString, NSDate, NSString, NSString),
...
)

我希望能够根据它们自己的任何元素对顶级数组的元素进行排序.我编写了以下代码来执行此操作,但是事实证明,对于我正在处理的大数据集而言,效率太低.

I would like to be able to sort the elements of the top level array based on any of of their own elements. I wrote the following code which does this, but has proven to be far too inefficient for the large data sets I am dealing with.

-(NSMutableArray *) sortArrayByDate:(NSMutableArray *) unsortedArray {

    NSMutableArray * sortedArray = [[NSMutableArray alloc ] init ];

    while ([unsortedArray count]>0) {
        int topIndex = 0;
        NSDate * topDate = [[NSDate alloc] initWithString:@"1970-01-01 00:00:00 +0600"];
        for(int j=0;j<[unsortedArray count];j++) {
            NSDate * targetDate = [[unsortedArray objectAtIndex:j] objectAtIndex:1];
            if ([targetDate compare:topDate] == NSOrderedDescending) {
                topDate = targetDate;
                topIndex = j;
            }            
        }
        [sortedArray addObject:[unsortedArray objectAtIndex:topIndex]];
        [unsortedArray removeObjectAtIndex:topIndex];        
    }    
    return sortedArray;
}

任何人都可以对如何使用更完善的sortUsingSelector或sortUsingDescriptor方法完成此任务提出建议吗?如果我要对一维数组进行排序,我认为它将是这样的:

Can anyone please make a suggestion on how to accomplish this task using the more established methods of either sortUsingSelector or sortUsingDescriptor? If I was sorting a 1D array I think it would be something like:

[unsortedArray sortUsingSelector: @selector(compare:)]

但是如何告诉它使用我要传递的数组的第n个值进行排序?

but how do I tell it to sort using the nth value of the array I am passing it?

-非常感谢

-非常感谢

推荐答案

在大多数情况下,您将创建一个对象:

in most cases, you would create an object:

@interface MONObject : NSObject
{
  NSString * a;
  NSDate * b;
  NSString * c;
  NSString * d;
}
...

然后教它与其他对象进行比较,然后在数组中使用这些对象.数据的逻辑组织和实现.

then teach it to compare itself to others, then use those objects in the array. logical organization of data and implementation.

这篇关于Objective-C,对多维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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