Objective-C, sorting muti-dimensional arrays

后端 未结 2 1436
清酒与你
清酒与你 2021-01-23 21:32

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:

(         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-23 21:33

    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.

提交回复
热议问题