Goal C - what is the use of a non-empty block?

I have seen many blocks with a void return type. But you can declare non-empty blocks. What is the use 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 the declaration above the block, what is the purpose of NSString to return the block type? How can I use the return value ("ret val")?

+5
source share
2 answers

You can use non-empty blocks for the same reason as a non-void pointer to provide an additional level of indirection when it comes to code execution.

NSArray sortUsingComparator gives one example of this 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 allows you to encapsulate the comparison logic outside the method sortedArrayUsingComparatorthat performs the sorting.

+11
source

, - , .

-(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);
}
+4

All Articles