Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an objective-c method that return a block

Tags:

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

How would I do so?

I tried

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

Let's just say it doesn't work yet.

like image 384
user4951 Avatar asked Nov 02 '12 10:11

user4951


People also ask

What is the use of block in Objective-C?

Blocks are a language-level feature added to C, Objective-C and C++, which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. Blocks are Objective-C objects, which means they can be added to collections like NSArray or NSDictionary .

What is Objective-C blocks called in Swift?

Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.


1 Answers

A method signature to return a block like this should be

+(NSInteger (^)(id, id))comparitorBlock {     .... } 

This decomposes to:

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

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

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

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

+ (NSComparator)comparator {    .... } 
like image 190
WDUK Avatar answered Sep 30 '22 07:09

WDUK