Mobile Development 15 min read

Unlocking the Secrets of Objective‑C Blocks: From Syntax to Runtime Mechanics

This article demystifies Objective‑C blocks by explaining their definition, practical uses, syntax variations, common usage scenarios, underlying data structures and compilation process, copy semantics, variable capture rules, reference‑cycle pitfalls, and provides concise code examples and reference links for iOS developers.

Sohu Smart Platform Tech Team
Sohu Smart Platform Tech Team
Sohu Smart Platform Tech Team
Unlocking the Secrets of Objective‑C Blocks: From Syntax to Runtime Mechanics

Block

Prologue: describing the most difficult technology in the simplest language.

Recently while learning and migrating Swift code I encountered the closure section; after reading it I was fascinated, so I wrote these two articles. If any statements are vague or inaccurate, please contact [email protected] .

Table of Contents

What is Block

What is Block used for

Syntax

Usage scenarios

Principle

Block data structure and compilation process

Copy of Block

Captured variables

Precautions

Reference documents

Conclusion

What is Block

Block

is a closure implementation in Objective‑C. A closure has two features: it captures referenced local variables and contains a code block.

In the Apple source file Block_private.h you can see a struct that contains an isa pointer, so in Objective‑C it can be regarded as an object.

The syntax is essentially an anonymous function in Objective‑C.

What is Block used for

Summary: optional passing of parameters to achieve callback functionality.

Syntax

As a local variable

returnType (^blockName)(parameterTypes) = ^returnType(parameters) {...};
// example
void (^successBlock)(NSDictionary *params) = ^void(NSDictionary *params) {...};

As a property

@property (nonatomic, copy, nullable) returnType (^blockName)(parameterTypes);
// example
@property (nonatomic, copy, nullable) void (^failBlock)(NSError *error);

As a method parameter

- (void)someMethodThatTakesABlock:(returnType (^nullability)(parameterTypes))blockName;
// example
- (void)URLRequestCompletion:(void (^ _Nullable)(NSDictionary *))successBlock {...}

As a callback after a method

[someObject someMethodThatTakesABlock:^returnType (parameters) {...}];
// example
[UIView animateWithDuration:0.5f animations:^(void){ /* ... */ }];

As a C function parameter

void SomeFunctionThatTakesABlock(returnType (^blockName)(parameterTypes));
// example
void testCFunc(void (^successBlock)(char *name)) { ... }

As a type alias

typedef returnType (^TypeName)(parameterTypes);
// example
successBlock block = ^void(NSDictionary *params) { ... };

Usage Scenarios

Delayed execution

Time‑consuming tasks

Background tasks

Extending the lifecycle of instances or objects

Principle

Block data structure and compilation process

To understand the underlying principle we need to see how the compiler processes the high‑level code. The clang command is used.

Environment: Apple clang version 12.0.5 (clang‑1205.0.22.11), Xcode Version 12.5.1 (12E507)

Project preparation steps (create project, select macOS → Command Line Tool, set product name and language to Objective‑C) – illustrated with images.

Compile the source file with clang and inspect the generated structures.

// Block description
struct Block_descriptor_1 {
    uintptr_t reserved;
    uintptr_t size;
};
// Block layout
struct Block_layout {
    void *isa;
    volatile int32_t flags;
    int32_t reserved;
    void (*invoke)(void *, ...);
    struct Block_descriptor_1 *descriptor;
    // captured variables
};

Further analysis shows the generated C functions corresponding to the block, such as __main_block_func_0, and the copy and dispose helpers.

About Block copy

The block is initially created on the stack ( _NSConcreteStackBlock). When the block needs to outlive the stack frame it is copied to the heap ( _NSConcreteMallocBlock) and the captured objects are retained.

// Pseudo‑code for Block_copy
Block_layout *result = malloc(aBlock->descriptor->size);
memmove(result, aBlock, aBlock->descriptor->size);
result->isa = _NSConcreteMallocBlock;
_Block_call_copy_helper(result, aBlock);
return result;

About captured variables

Variables captured by a block can be:

Global static variables (always in the global data segment, address unchanged)

Global variables (same as above)

Local static variables (extend the lifetime of the local variable)

Automatic (local) variables (captured by value; after the function returns the stack is destroyed, so the block must copy them to the heap to keep them alive)

The article demonstrates how each category is stored and how copying affects them.

Precautions

Reference cycles can occur when a block captures self strongly. Use __weak or __block to break the cycle.

__weak typeof(self) weakSelf = self;
self.print_name = ^(NSString *name) {
    weakSelf.view.backgroundColor = [UIColor redColor];
    NSLog(@"name is %@", name);
};

Alternatively, use __block to move the captured variable to the heap and set it to nil after use.

__block ViewController *blockSelf = self;
self.print_name = ^(NSString *name) {
    blockSelf.view.backgroundColor = [UIColor redColor];
    blockSelf = nil;
    NSLog(@"name is %@", name);
};

Conclusion

Alright, that’s a lot about iOS blocks. There are still deeper details to explore, but I hope we can ride the wave together. The next article will cover closures.

Reference Documents

https://blog.ibireme.com/2013/11/27/objc-block/

https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html

https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

iOSmemory managementCompilationObjective‑CclosureBlocks
Sohu Smart Platform Tech Team
Written by

Sohu Smart Platform Tech Team

The Sohu News app's technical sharing hub, offering deep tech analyses, the latest industry news, and fun developer anecdotes. Follow us to discover the team's daily joys.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.