7

I am quite confused about how to change an instance variable inside of a block.

The interface file (.h):

@interface TPFavoritesViewController : UIViewController {
    bool refreshing;
}

The implementation:

__weak TPFavoritesViewController *temp_self = self;
refreshing = NO;
[myTableView addPullToRefreshWithActionHandler:^{
    refreshing = YES;
    [temp_self refresh];
}];

As you might guess, I get a retain cycle warning when I try to change the refreshing ivar inside of the block. How would I do this without getting an error?

Keiran Paster
  • 600
  • 2
  • 7
  • 21

1 Answers1

6

Your assignment to refreshing is an implicit reference to self, it is shorthand for:

self->refreshing = YES;

hence the cycle warning. Change it to:

temp_self->refreshing = YES;
CRD
  • 52,522
  • 5
  • 70
  • 86
  • 2
    It doesn't build with only this code. I get the following error: Dereferencing a __weak is not allowed due to possible null value caused by a race condition, assign it to a strong variable first. I think I got it working by adding this: __strong TPRideListView *strong_self = temp_self; strong_self->refreshing = YES; – Keiran Paster Aug 01 '12 at 04:49
  • 1
    Careful; dereferencing a weak pointer can lead to crashes. Better to make a strong pointer from the weak one inside the block, check for nil, and use that. – BJ Homer Aug 01 '12 at 04:50
  • @KeiranPaster - apologies I missed the second warning; if your code keeps the warnings at bay its fine, you have it working *provided* your object is staying around (i.e. `self` is valid); the code does not deal with the possibility of a `nil` value. I assume you know it is, if you don't... – CRD Aug 01 '12 at 10:23