I’ve seen many blocks with void return type. But it’s possible to declare non-void blocks. Whats the usage of this?
Block declaration,
-(void)methodWithBock:(NSString *(^)(NSString *str))block{
// do some work
block(@"string for str"); // call back
}
Using the method,
[self methodWithBock:^NSString *(NSString *str) {
NSLog(str); // prints call back
return @"ret val"; // <- return value for block
}];
In above block declaration , what exactly is the purpose of NSString return type of the block? How the return value ( “ret val”) can be used ?
You can use non-void blocks for the same reason you’d use a non-void function pointer – to provide an extra level of indirection when it comes to code execution.
NSArray‘ssortUsingComparatorprovides one example of such use:The comparator block lets you encapsulate the comparison logic outside the
sortedArrayUsingComparatormethod that performs the sorting.