0

I went through some of these articles about ARC in OBJ-C (https://dhoerl.wordpress.com/2013/04/23/i-finally-figured-out-weakself-and-strongself/, http://tech.pro/tutorial/1227/blocks-gcd-and-pitfalls-to-avoid, Always pass weak reference of self into block in ARC?), however these things are still unclear to me:

- (NSArray *)rightButtons{
    __typeof(self) __weak weakSelf = self;
    JAActionButton *button1 = [JAActionButton actionButtonWithTitle:@"Archive" color:kArchiveButtonColor handler:^(UIButton *actionButton, JASwipeCell*cell) {
        [cell completePinToTopViewAnimation];
        [weakSelf rightMostButtonSwipeCompleted:cell];
    }];

    return @[button1];
}

button1 is inside the lexical scope of rightButtons method. It is not a property on this class. WHY do I need to pass weakSelf to the block then? Does the compiler see button1 as self.button1 (which would then make sense to use weakSelf within the block)? How does self retain this block so that you need weakSelf?

Community
  • 1
  • 1
  • Who said you needed `weakSelf` inside the block? You shouldn't in this case. Did you try it without the weak reference? Are there any problems (such as a reference cycle)? – rmaddy May 21 '15 at 21:32

1 Answers1

0

Self might not directly have a reference to button1, but it's possible that self has a reference to something else that has a reference to button1.

Something like: self --> view --> button1 --> self

Aaron
  • 188
  • 2
  • 8
  • Aaah yes that makes perfect sense then! How about in this case http://stackoverflow.com/questions/20030873/always-pass-weak-reference-of-self-into-block-in-arc. The first code snippet (handleNewerData method) doesn't need weakSelf in that block right? – Andrzej May 21 '15 at 21:45
  • If you assume the operation finishes successfully, then the queue should release it and break any possible retain loop. If, for some strange reason, the queue never runs the operation, and self has a reference to the queue, then could you end up with a retain loop. In practice, I almost always use a weak reference to self within blocks, even if it's not strictly necessary. Unless you specifically need the block to keep self alive, then it won't make a difference. – Aaron May 21 '15 at 21:55
  • How about that weakSelf & strongSelf dance? When do you use that? – Andrzej May 21 '15 at 22:03
  • Do you mean the response by Ilker Baltaci in the link? As far as I can tell, that only matters if the block is executed concurrently. If self gets dealloc'd in the middle of block execution, you could potentially get funky behavior. Defining a strong reference at the beginning of block execution would prevent that. – Aaron May 21 '15 at 22:30