openfrog
openfrog

Reputation: 40755

Can I really check an instance variable in a block like this?

This tutorial suggests that you can do this:

dispatch_async(queue, ^{
    if (_valid) {
        [self processFile:fileURL];
    }
});

But I am skeptical. Blocks copy the value of the variables (capturing scope). So _valid would be YES or NO depending on what it was when I created this block. The block would use this captured value and not look up the actual value of the instance variable. Correct?

Upvotes: 2

Views: 94

Answers (1)

Kevin
Kevin

Reputation: 56129

The block would use this captured value and not look up the actual value of the instance variable. Correct?

No. In the case of instance variables, self is captured and the instance variable is evaluated as self->_valid, i.e. the value at the time the block is run.

This is why you get a warning from ARC in some cases like this, about implicitly capturing self can cause a reference cycle.

This is also another reason you should always use the properties, not the instance variables directly. It makes it clear and explicit that self is captured, not the property.

Upvotes: 5

Related Questions