如何创建返回块的objective-c方法

use*_*951 18 block objective-c objective-c-blocks

-(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;
}
Run Code Online (Sandbox Code Playgroud)

所以基本上我有这个用于排序数组的块.

现在我想编写一个返回该块的方法.

我该怎么办?

我试过了

+ (NSComparator)(^)(id obj1, id obj2)
{
    (NSComparator)(^ block)(id obj1, id obj2) = {...}
    return block;
}
Run Code Online (Sandbox Code Playgroud)

我们只是说它不起作用.

WDU*_*DUK 54

返回像这样的块的方法签名应该是

+(NSInteger (^)(id, id))comparitorBlock {
    ....
}
Run Code Online (Sandbox Code Playgroud)

这分解为:

+(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
Run Code Online (Sandbox Code Playgroud)

更新:在您的特定情况下,NSComparator已经是块类型.它的定义是:

typedef NSComparisonResult (^NSComparator)(id obj1, id obj2);
Run Code Online (Sandbox Code Playgroud)

因此,您需要做的就是返回此typedef:

+ (NSComparator)comparator {
   ....
}
Run Code Online (Sandbox Code Playgroud)

  • 不.`NSComparator`已经是块类型.你可能意味着`+(NSComparisonResult(^)(id,id))比较器`或`+(NSComparator)比较器`. (3认同)