Search code examples
iosuiviewuikitcore-animation

Block scoping of self and dot accessors inside animateWithDuration block method of UIView


Is it safe to access self and self's properties via dot accessors inside of an animateWithDuration block?

I'm having some animation glitches related to expanding self frame especially when I call self.frame, as in below:

[UIView animateWithDuration:timeInterval animations:^{
    self.citiesTableView.frame = CGRectMake(0, 100, 320, 120);
    self.frame = CGRectMake(0, 0, 320, 220);
} completion:^(BOOL completed){
    if (completed) {
        self.citiesTableView.frame = CGRectMake(0, 100, 320, 120);
        self.frame = CGRectMake(0, 0, 320, 220);
        [self.citiesTableView reloadData];
    }
}];

Solution

  • Since the block isn't retained by the view, it is safe to capture self strongly inside the block. Problems arise, when blocks capture self strongly (intentionally or by mistake, by accessing instance variables) and are retained by the view, like for instance, when using a block as the response of a bar button item. Here, the block is executed and discarded.