21
-(NSMutableArray *)sortArrayByProminent:(NSArray *)arrayObject
{
    NSArray * array = [arrayObject sortedArrayUsingComparator:^(id obj1, id obj2) {
        Business * objj1=obj1;
        Business * objj2=obj2;
        NSUInteger prom1=[objj1 .prominent intValue];
        NSUInteger prom2=[objj2 .prominent intValue];
        if (prom1 > prom2) {
            return NSOrderedAscending;
        }
        if (prom1 < prom2) {
            return NSOrderedDescending;
        }
        return NSOrderedSame;
    }];

    NSMutableArray *arrayHasBeenSorted = [NSMutableArray arrayWithArray:array];

    return arrayHasBeenSorted;
}

So basically I have this block that I use to sort array.

Now I want to write a method that return that block.

How would I do so?

I tried

+ (NSComparator)(^)(id obj1, id obj2)
{
    (NSComparator)(^ block)(id obj1, id obj2) = {...}
    return block;
}

Let's just say it doesn't work yet.

user4951
  • 32,206
  • 53
  • 172
  • 282
  • Exactly what do you mean by "it doesn't work"? That's way too broad for a proper error description. –  Nov 02 '12 at 10:45

1 Answers1

58

A method signature to return a block like this should be

+(NSInteger (^)(id, id))comparitorBlock {
    ....
}

This decomposes to:

+(NSInteger (^)(id, id))comparitorBlock;
^^    ^      ^  ^   ^  ^       ^
ab    c      d  e   e  b       f

a = Static Method
b = Return type parenthesis for the method[just like +(void)...]
c = Return type of the block
d = Indicates this is a block (no need for block names, it's just a type, not an instance)
e = Set of parameters, again no names needed
f = Name of method to call to obtain said block

Update: In your particular situation, NSComparator is already of a block type. Its definition is:

typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);

As such, all you need to do is return this typedef:

+ (NSComparator)comparator {
   ....
}
WDUK
  • 18,870
  • 3
  • 64
  • 72
  • 3
    Nope. `NSComparator` is already a block type. You probably meant either `+ (NSComparisonResult (^)(id, id))comparator` or `+ (NSComparator)comparator`. –  Nov 02 '12 at 11:04
  • Oops, oversight! Thanks. Yeah, I'd go with `+ (NSComparator)comparator` out of the two, for this question at least. – WDUK Nov 02 '12 at 11:09
  • Great. Selected and +1. Thanks a lot. I just do not want to select answers that's still wrong given that most people don't read commenbts. It'll confuse other readers :) – user4951 Nov 03 '12 at 17:03