我如何创建一个返回块的Objective-C方法 [英] How do I create an objective-c method that return a block

查看:80
本文介绍了我如何创建一个返回块的Objective-C方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我该怎么办?

我尝试过

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

让我们说这还行不通.

推荐答案

返回这样的代码块的方法签名

A method signature to return a block like this should be

+(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已经是块类型.其定义是:

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

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

这样,您所需要做的就是返回此typedef:

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

+ (NSComparator)comparator {
   ....
}

这篇关于我如何创建一个返回块的Objective-C方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆