如何创建一个返回块的 Objective-C 方法?

22
-(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;
}

基本上,我有一个用于排序数组的代码块。

现在我想编写一个方法来返回该代码块。

我该如何实现呢?

我尝试了:

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

我们就说它目前还没有起作用吧。


你所说的“它不起作用”具体指什么?这种描述太过笼统,无法提供正确的错误描述。 - user529758
1个回答

58
返回这样的块的方法签名应该是:
+(NSInteger (^)(id, id))comparitorBlock {
    ....
}

这可以分解为:

+(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

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

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

因此,你需要做的就是返回这个 typedef:
+ (NSComparator)comparator {
   ....
}

3
不,NSComparator已经是一个块类型。你可能想要的是+ (NSComparisonResult (^)(id, id))comparator或者+ (NSComparator)comparator - user529758
糟糕,疏忽了!谢谢。是的,至少对于这个问题,我会选择+ (NSComparator)comparator - WDUK
太好了。已选择并+1。非常感谢。我只是不想选择仍然错误的答案,因为大多数人不会阅读评论。这会让其他读者感到困惑 :) - user4951

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接