Call function in a block save cycle

If the function that I called from inside the block refers to "I", will it create a save loop?

__weak id weakSelf = self; - (void)firstFunction { id strongSelf = weakSelf; if (!strongSelf) return; [anObject performBlock:^{ [strongSelf secondFunction]; }]; } - (void)secondFunction { [self doSomeCrazyStuff]; self.counter++; //etc. } 

I call "self" in "secondFunction", do I need to pass my weak pointer to this function and use it instead?

+4
source share
2 answers

Potentially.

The save cycle is created using a cycle of strong links, in addition to the qualifier (i.e., weak, strong) for the variable, the actual variables in which these links come in do not matter. Therefore, the strongSelf referenced by your block is a strong reference to self , and you have the same potential for the save loop as if you were using self .

Re: comment

If your block supports a weak link, this is the standard approach to solving this problem. If you use weakSelf in your block, then there is no strong link, if by the time the block is called weakSelf , there is nil , then calling [weakSelf secondFunction] do nothing - you are allowed to nil in Objective-C. You will not create a loop; during the call of the block, a strong copy of the link can be created, but this will happen after the call returns to the block.

+1
source

I could be wrong, but I do not see a save cycle here.

Blocks are a stack if they are not copied to the heap.

I do not use ARC, so your mileage may vary, but at least without ARC I would not expect a save cycle when the block was allocated with stacks and it does not have a saved reference to self.

The self reference will be copied onto the block stack, and if it goes outside the scope, the block will continue to access the copy until the block completes.

I don’t think I know how ARC manages this, I believe that if you are going to use ARC, you should know how it works.

But as regards non-ARC code, I do not see a save loop in this code.

0
source

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


All Articles