Changing an instance variable in a block
Asked Answered
K

1

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?

Kamerad answered 1/8, 2012 at 4:19 Comment(0)
W
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;
Wilkison answered 1/8, 2012 at 4:43 Comment(3)
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;Kamerad
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.Denison
@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...Wilkison

© 2022 - 2024 — McMap. All rights reserved.