简体   繁体   中英

Block stored as instance variable becomes nil

I'm trying to store a block in an instance variable in my project. Here's where I declare the instance variable:

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

I'm assigning the 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 the debugger with type NSMallocBlock . However, when I actually need to run the block after the login alert view is returned, it has become nil.

I've tried:

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

What am I missing?

Blocks are the only objects (to date) created on the stack rather than the heap. If you want to keep a block around longer than the life of the stack frame in which it was created, you must copy the block (the copy is heap based). Even using a strong pointer will not stop the block from going away when the stack frame is popped.

ADDED: the comments are correct, having a copy property is sufficient. My bad, I forgot the copy attribute was there.

Turns out it had nothing to do with storing the block incorrectly. I was actually creating a new object of the same class as the one that stored the block but forgot to copy over the actual block. Thus, the methods that were being hit that logged out the value of self.loginCompletedBlock were being received by the other object rather than the one that assigned the variable to begin with.

Thanks all for your help, it always amazes me how SO users are so willing to help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM