Blocks, Stacks and Heaps

Using Xcode 4.2 and ARC, I wrote the following code before I had an understanding of how blocks need to be copied from stack to heap.

-(void) downloadWithBlock:(void (^)(void))callbackBlock; { // start the data download in the background... NSOperation *backgroundOperation = [NSBlockOperation blockOperationWithBlock:^{ // synchronous download code }]; [backgroundOperationQueue addOperation:backgroundOperation]; NSOperation *foregroundOperation = [NSBlockOperation blockOperationWithBlock:^{ callbackBlock(); }]; [foregroundOperation addDependency:backgroundOperation]; [[NSOperationQueue mainQueue] addOperation:foregroundOperation]; } 

The code works, but I don’t trust it because I don’t understand it. In another section of code, I ran into application crashes when calling blocks that were saved in ivars without using -copy. This made me wonder if this section of code should be rewritten as follows:

 -(void) downloadWithBlock:(void (^)(void))callbackBlock; { void(^heapBlock)(void) = [callbackBlock copy]; // start the data download in the background... NSOperation *backgroundOperation = [NSBlockOperation blockOperationWithBlock:^{ // synchronous download code }]; [backgroundOperationQueue addOperation:backgroundOperation]; NSOperation *foregroundOperation = [NSBlockOperation blockOperationWithBlock:^{ heapBlock(); }]; [foregroundOperation addDependency:backgroundOperation]; [[NSOperationQueue mainQueue] addOperation:foregroundOperation]; } 

My only problem is to better understand how block pointers work. Is any of these sections of code acceptable? Does the compiler call the block in another block to insert the hidden Block_copy operation?

+4
source share
1 answer

Not only the call of the block inside the block, but any direct link to it will cause a copy. Including passing it as an argument to something else. The same applies to ObjC types in a block (except for a simple save, not a copy for them).

+1
source

Source: https://habr.com/ru/post/1386316/


All Articles