1

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]];
user692942
  • 16,398
  • 7
  • 76
  • 175
user1743514
  • 311
  • 1
  • 3
  • 21

2 Answers2

1

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];
alltom
  • 3,162
  • 4
  • 31
  • 47
  • Why the `NSMutableArray arrayWithArray` bit? – Droppy Jul 31 '14 at 10:05
  • I copied it from the question without thinking too hard about it. I would probably use `mutableCopy` instead. I s'pose I should clean that up... – alltom Jul 31 '14 at 19:19
0

altom's answer gave me a build error, "Returning block that lives on the local stack".

That can be resolved by wrapping the block in Block_copy() as in nielsbot's answer to a similar question.

This example is using MRR rather than ARC, so an autorelease was added.

static NSComparator blockWithViewController(UIViewController *viewController) {
    return [Block_copy(^NSComparisonResult (id object1, id object2) {
        NSLog(@"view controller is %@", viewController);
        return NSOrderedSame;
    }) autorelease];
}
jk7
  • 1,958
  • 1
  • 22
  • 31