Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - what is the usage of a non-void block?

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 ?

like image 686
Rukshan Avatar asked Feb 06 '13 19:02

Rukshan


People also ask

What is the purpose 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 does void mean in Objective-C?

The (void) indicates the return type. This method doesn't return anything, so its result can't be assigned to anything.

What does __ block do?

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.

How do you declare a block in Objective-C?

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.


2 Answers

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.

like image 194
Sergey Kalinichenko Avatar answered Oct 16 '22 16:10

Sergey Kalinichenko


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);
}
like image 35
Ryan Poolos Avatar answered Oct 16 '22 14:10

Ryan Poolos