Search code examples
objective-cblock

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 ?


Solution

  • 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.