Objective-C, sorting muti-dimensional arrays

一世执手 提交于 2019-12-02 04:31:07

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!