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 ?
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 .
The (void) indicates the return type. This method doesn't return anything, so its result can't be assigned to anything.
The __block Storage Type __block variables live in storage that is shared between the lexical scope of the variable and all blocks and block copies declared or created within the variable's lexical scope.
Declaring Block VariablesStart with a return type followed by the variable name and a parameter list. You'll need a caret (^) before the variable name and two sets of parentheses. With that in mind, the following example declares a completion block, identical to the one you just saw, but without using custom typedefs.
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
's sortUsingComparator
provides one example of such use:
NSArray *sorted = [originalArray sortedArrayUsingComparator:(NSComparator)^(id obj1, id obj2){
NSString *lhs = [obj1 stringAttribute];
NSString *rhs = [obj2 stringAttribute];
return [lhs caseInsensitiveCompare:rhs];
}];
The comparator block lets you encapsulate the comparison logic outside the sortedArrayUsingComparator
method that performs the sorting.
It's just a return, so you could do something like this to take advantage of the return value and do work on it as well.
-(void)methodWithBlock:(NSString *(^)(NSString *str))block{
// do some work
NSString *string = block(@"string for str"); // call back
// do something with the return string
NSLog(@"%@",string);
}
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