objective-c - 如何创建一个返回 block 的 objective-c 方法

标签 objective-c block 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;
}

所以基本上我有这个 block 用于对数组进行排序。

现在我想编写一个返回该 block 的方法。

我该怎么做?

我试过了

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

我们就说它还行不通吧。

最佳答案

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

+(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 已经是 block 类型。它的定义是:

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

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

+ (NSComparator)comparator {
   ....
}

关于objective-c - 如何创建一个返回 block 的 objective-c 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13193673/

相关文章:

objective-c - 如何用 arg 写 block 。 Swift 闭包中的 "UnsafeMutablePointer<UnsafeMutablePointer<Float>>"

block - CSS block 并排

java - 将 objective-c 面向 block 的 api 转换为 android

ios - 无法访问 dispatch_async : "Variable is not Assignable (missing _block type specifier)" 中的全局变量

iOS 框架 : what is ABT (ABTViewSelectorComponent, ABTWeakValue、ABTDestructonomicon 等)?

iphone - 动态调用私有(private) API 而不被 App Store 注意到

ios - 如何通过 API 调用使用 ChimpKit for iOS 添加到 MailChimp 列表而不验证电子邮件?

html - 全宽( block )按钮不会在 IE 中显示样式

Objective-c : How method using block can returns object

objective-c - 将 block 传递给 AFNetworking 方法?