Open In App

Blocks in Objective-C

Last Updated : 04 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Blocks in Objective-C are a potent tool that can simplify the development process. Blocks are an alternative to traditional functions, allowing you to write code that is more concise and efficient. They are used for many different purposes, including as callbacks and iterators. Blocks can also be used to create custom objects and pass data between objects. Blocks are an essential concept to understand when working with Objective-C, as they are widely used in the language.

Blocks are self-contained pieces of code that can be passed around and used just like any other object in Objective-C. They are similar to functions in that they take arguments, execute code, and return a value. However, they can also be assigned to variables and passed as arguments to other methods. Blocks have access to variables in the scope in which they are defined, allowing them to access and modify them. Blocks can be used to greatly reduce the amount of code that needs to be written, as they allow code to be written in a more concise and efficient manner.

Types of Blocks

Three main types of blocks can be used in Objective-C: standard blocks, typed blocks, and auto-releasing blocks. 

Standard Blocks

Standard blocks are blocks that are declared with the block keyword. They are used to control the flow of execution. They can be used to execute code in a specific order, execute multiple pieces of code at the same time, and more.

  • Standard blocks are the most common type of block and are used for basic operations, such as looping and executing code
  • A standard block is a block that has no specific return type or arguments.

Syntax of Standard block

^(int a, int b){

  int c = a + b;

  return c;

}

The ^ symbol is used to denote that the following code is a block. 

The int a and int b are the arguments that the block can take, and the int c 

is a variable that is declared within the block and returned at the end.

Typed Blocks

Typed blocks are blocks that are declared with a specific type associated with them. This type can be any Objective-C type such as int, float, double, etc. Typed blocks are used to define specific behavior for a certain type of data.

  •  Typed blocks are used when you need to specify the type of the argument and the return type of the block.
  • A typed block is a block that has a specific return type and argument type. 

Syntax of Typed block

Typed block that takes two ints and returns an int:

^int(int a, int b) {

  int c = a + b;

  return c;

}

This block takes two ints, adds them together, and then returns the result.

Autoreleasing Blocks

Autoreleasing blocks are blocks that are declared with the __autoreleasing keyword. This keyword is used to indicate that the block will be automatically released when it is no longer needed. Autoreleasing blocks are used for memory management in Objective-C.

  •  Autoreleasing blocks are used when you need to release the block after the method is finished.
  • An auto-releasing block is a block that has a local scope and is automatically released when it goes out of scope

Syntax of Auto-releasing Block

Auto-releasing block that takes one int and returns an int:

@autoreleasepool {

   ^int(int a) {

       int b = a + 1;

       return b;

   }

}

This block takes an int, adds one to it, and then returns the result.

Example 1:

ObjectiveC




// Standard Block
int (^multiply)(int, int) = ^(int num1, int num2) {
    return num1 * num2;
};
  
int result = multiply(3, 5); // result is 15
  
// Typed Block
typedef int (^AdditionBlock)(int, int);
  
AdditionBlock add = ^(int num1, int num2) {
    return num1 + num2;
};
  
int sum = add(3, 5); // sum is 8
  
// Autoreleasing Block
@autoreleasepool {
    NSString *string = @"Hello, world!";
      
    void (^printString)(void) = ^{
        NSLog(@"%@", string);
    };
      
    printString();
}


Output:

Output

 

In this example, the multiply block is a standard block that takes two integer parameters and returns their product. The add block is a typed block that is declared using a typedef statement and takes two integer parameters and returns their sum. Finally, the printString block is an auto-releasing block that prints a string to the console.

 In the example, the multiply block is a standard block.

 In the example, the add block is a typed block.

 In the example, the printString block is an auto-releasing block because it is declared within an @autoreleasepool statement.

Example 2:

ObjectiveC




#import <Foundation/Foundation.h>
  
// Block with no parameters and no return value
typedef void (^SimpleBlock)(void);
  
// Block with one parameter and no return value
typedef void (^ParameterBlock)(NSString *);
  
// Block with no parameters and a return value
typedef int (^ReturnBlock)(void);
  
int main(int argc, const char * argv[]) {
    @autoreleasepool {
          
        // SimpleBlock implementation
        SimpleBlock simpleBlock = ^{
            NSLog(@"Welcome to GeeksForGeeks");
        };
        simpleBlock(); // Output: "Welcome to GeeksForGeeks"
          
        // ParameterBlock implementation
        ParameterBlock parameterBlock = ^(NSString *name) {
            NSLog(@"Hello, %@!", name);
        };
        parameterBlock(@"John"); // Output: "Hello, John!"
          
        // ReturnBlock implementation
        ReturnBlock returnBlock = ^{
            return 42;
        };
        int result = returnBlock();
        NSLog(@"The result is %d", result); // Output: "The result is 42"
          
        // Block with both parameters and return value
        int (^AdditionBlock)(int, int) = ^(int a, int b) {
            return a + b;
        };
        int sum = AdditionBlock(3, 5);
        NSLog(@"The addition of 3 and 5 is %d", sum); // Output: "The addition of 3 and 5 is 8"
    }
    return 0;
}


 Output:

Output

 

Explanation:

Using the typedef keyword, we first declare the various block types in this code. There are four types of blocks: a SimpleBlock, a ParameterBlock, a ReturnBlock, and a block with two parameters and a return value for addition. The SimpleBlock has no parameters and no return value.

Next, using the syntax, which stands for a block, we implement each form of block.

The Foundation framework’s NSLog() method, which publishes messages to the console, is used to output the outcomes of each block.

Conclusion

Blocks are a powerful tool in Objective-C that can simplify the development process. They can be used for a variety of purposes, such as callbacks and iterators. Blocks can also be used to pass data between objects and create custom objects. Blocks are an essential concept to understand when working with Objective-C, as they are widely used in the language.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads