-(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.
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 .
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.
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 { .... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With