Search code examples
iossortingnsmutablearray

NSMutableArray sorting -- passing parameter to comparitor block


I need to sort the array of string and want to access viewController property in the comparator block. So, Planning to pass ViewController object to comparator block. How to pass parameter to comparator block ?

Here is the Code.

Since comparator logic is lengthy and sorting is used many places, I can't expand comparatorBlock in the declaration.

sortedArray = [NsMutableArray arrayWithArray:[unsortedArray sortedArrayWithOptions:0 usingComparator:comparatorBlock]];

Solution

  • If you define the block in a method of the view controller, then it should be able to access self.

    If you can't do that, you can create a function that returns the block and captures the view controller as a function argument:

    static NSComparator blockWithViewController(UIViewController *viewController) {
        return ^NSComparisonResult (id object1, id object2) {
            NSLog(@"view controller is %@", viewController);
            return NSOrderedSame;
        };
    }
    

    You'd use it like this:

    NSMutableArray *sortedArray = [[unsortedArray sortedArrayWithOptions:0 usingComparator:blockWithViewController(viewController)] mutableCopy];