1. The nature of blocks

A Block is an object that encapsulates a function and since a Block encapsulates a function inside of it.

Inside the block, the code that needs to be executed is converted into a function function, which is then held by the block_impl structure, and the function function of the block is called during execution.

Second, block code structure

Iii. Block related knowledge

1. Block’s variable capture mechanism

2. Block type

Under the MRC are:

  • GlobalBlock does not reference any external variables.
  • A StackBlock refers to external variables.
  • MallocBlock (heap) copies stack blocks.

The ARC under:

  • Block autocopy, no stack Block, only heap Block and global Block.

3. Copy of block

4. Object type auto variable

5. __block modifier

6. The object type modified by __block

7. Block several ways to solve circular references

8. There are several ways to call blocks

void (^block)(void) = ^ {

 NSLog(@"block get called");

 };





 //1. blcok()

 block();





 //2. Use other methods to execute blocks

 [UIView animateWithDuration:0 animations:block];





 / / 3.

 [[NSBlockOperation blockOperationWithBlock:block] start];





 //4. NSInvocation

 NSMethodSignature *signature = [NSMethodSignature signatureWithObjCTypes:"v@?"];

 NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];

 [invocation invokeWithTarget:block];





 //5.DLIntrospection invoke

 [block invoke];





 //6. Pointer call

 void *pBlock = (__bridge void *)block;

 void (*invoke)(void*,...). = * ((void **)pBlock + 2);

 invoke(pBlock);





 / / 7. Use Clang

 __strong void(^cleaner)(void) __attribute ((cleanup(blockCleanUp),unused)) = block;





 //8. Inline a assembly to complete the call

 asm("callq *0x10(%rax)");





 static void blockCleanUp (__strong void (^*block)(void)) {

 (*block)();

 }

Copy the code