A block saved as an instance variable becomes nil

I am trying to save a block in an instance variable in my project. Here where I declare an instance variable:

@property (nonatomic, copy)void (^loginCompletedTask)(); 

I assign this variable by calling this method:

 - (void)requireLoggedInForBlock:(void (^)())completion { self.loginCompletedTask = completion; // Display an alert view that requires username and password input } 

After the first line of this method, self.loginCompletedTask is non-nil and logs in a debugger of type NSMallocBlock . However, when I really need to start the block after the login warning view is returned, it becomes null.

I tried:

  • strong declaration instead of copy ,
  • Setting self.loginCompletedTask = ^{completion();}; ,
  • Setting a variable directly, instead of using a property ( _loginCompletedTask = ... ).

What am I missing?

+4
source share
2 answers

It turns out that this has nothing to do with improper storage of the block. I actually created a new object of the same class as the one that stored the block, but forgot to copy it from the actual block. Thus, methods that were deleted that left the self.loginCompletedBlock value were received by another object, and not the one to which this variable was assigned.

Thanks to everyone for your help, it always amazes me how SO users so willingly help.

+1
source

Blocks are the only objects (today) created on the stack, not a bunch. If you want to save a block longer than the lifetime of the stack frame in which it was created, you must copy block (the copy is based on the heap). Even using a strong pointer will not stop block blocking when displaying a stack frame.

ADDED: comments are correct, availability of copy property is enough. My bad, I forgot that the copy attribute was there.

+1
source

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


All Articles