Simple block methods in Xcode for iOS: The secret of the caret

The mysterious caret can be confusing to see in other people's code. But taking the simple example from Apple's code of a basic block (which is what the caret signifies) we can explain a little more clearly the meaning.

    int (^Multiply)(int, int) = ^(int num1, int num2) {
        return num1 * num2;
    };

First to be understood, in the sample code, is that that the initial caret precedes the method name, next to which we have (int,int), which declares the number and type of variables accepted by the method. The second caret precedes the assignment of the variables to their given names for the purposes of the block. While at the very beginning of the line we have 'int', which is the thing returned by the method.

Let's think about what this would look like if it were a regular method:

-(int)Multiply:(int)num1 By:(int)num2 {
     return num1 * num2;
}

And we'd then call the method in this way:

   int result = [self Multiply:7 By:4]

But the purpose of the block approach is that the block is a discrete method that is called at any time within the method in which it is written. In the case of the block example in this post, it would be called like this:

    int result = Multiply(7, 4);

The example here demonstrates an approach that might be preferred but isn't required.

There are other areas of iOS where block methods are required, for example in the area of completion handlers, notifications and animations, and hence the need to learn about them. But the purpose of this post has merely been to help with the logic of blocks and those carets that are not at first glance very transparent.

Endorse on Coderwall

Comments