0

I am setting up a block which gets called on a custom UIButton press. I am assigning the block to the UIButton instance in viewDidLoad().

- (void) viewDidLoad{
   [super viewDidLoad];
   _customBTN.block = ^{
     self.test = @"Something";
   }
}

Should I keep the block on the stack since the block can only get called on a button press and that means viewDidLoad() would be on the stack, and this can be considered performant/best practice ... or am I doing something wrong?

aprofromindia
  • 1,111
  • 1
  • 13
  • 27

2 Answers2

1

Blocks don't stay on stacks (memory stack) and rather are copied (Objc objects referred inside block get a retain call (+1 retainCount) and scalar variables get copied) to heap when instantiated. It means when the line:

 _customBTN.block = ^{
     self.test = @"Something";
   };

is executed, stack frame created for viewDidLoad function got popped from the stack, self got a +1 retainCount and block was assigned to the block property of _customBTN, later on when _customBTN calls the block (on say button tapped event) the block is executed and it uses self and does what it does.

P.S. Its safe to use weak references to self when referring inside a block. weak wouldn't increase retainCount of self (which can lead to a retain cycles in worse cases).

Sabir Ali
  • 475
  • 2
  • 16
0

You can do it like this if there is no other choice. Also, do not use self in block. Create a week reference like this:

__weak typeof(self) weakSelf = self;

And use it in blocks:

_customBTN.block = ^{
  weakSelf.test = @"Something";
}
gontovnik
  • 690
  • 5
  • 9