【问题标题】:How do I create an objective-c method that return a block如何创建一个返回块的objective-c方法
【发布时间】:2012-10-23 00:29:00
【问题描述】:
-(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;
}

假设它还没有工作。

【问题讨论】:

  • “它不起作用”到底是什么意思?这对于正确的错误描述来说太宽泛了。

标签: objective-c block objective-c-blocks


【解决方案1】:

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

+(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 {
   ....
}

【讨论】:

  • 不。 NSComparator 已经是块类型。您的意思可能是+ (NSComparisonResult (^)(id, id))comparator+ (NSComparator)comparator
  • 糟糕,疏忽!谢谢。是的,至少对于这个问题,我会选择两者中的+ (NSComparator)comparator
  • 太棒了。已选中并 +1。非常感谢。鉴于大多数人不阅读评论,我只是不想选择仍然错误的答案。它会让其他读者感到困惑:)
猜你喜欢
  • 1970-01-01
  • 2019-09-04
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 2016-04-05
  • 2015-02-18
  • 1970-01-01
相关资源
最近更新 更多