Objective-C, sorting muti-dimensional arrays
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;
}
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:)]
but how do I tell it to sort using the nth value of the array I am passing it?
-Many thanks
-Many Thanks
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.
You can also use blocks-based method sortUsingComparator:
in NSMutableArray
like this –
[myArray sortUsingComparator:^(id first, id second){
id firstObject = [first objectAtIndex:1];
id secondObject = [second objectAtIndex:1];
return [firstObject compare:secondObject];
}]
You also have a parallel method sortedArrayUsingComparator:
in NSArray
which will spew out a sorted array.
Sorting by varying indices
typedef NSComparator (^ComparatorFactory)(id);
ComparatorFactory comparatorForIndex = ^NSComparator(id context) {
NSInteger index = [(NSNumber*)context integerValue];
NSComparator comparator = ^(id first, id second) {
id firstObject = [first objectAtIndex:index];
id secondObject = [second objectAtIndex:index];
return [firstObject compare:secondObject];
};
return [[comparator copy] autorelease];
};
[myArray sortUsingComparator:comparatorForIndex([NSNumber numberWithInteger:1])];
Depending on the index passed, the array will sort based on objects at that index. This is pretty basic code but you can add to this.
精彩评论