0xSina
0xSina

Reputation: 21563

Is this a retain cycle?

I usually get a warning when I call anything on self in a block retained by self:

[self.someView doSomething:^{
        self.aVar = @"Hello!";
    }];

I have to do:

        __weak SomeObject *weakSelf = self;
[self.someView doSomething:^{
        weakSelf.aVar = @"Hello!";
    }];

But if I call a method on weakSelf, and that method uses self, will that lead to a retain cycle even though I don't get a warning? I am talking about this:

        __weak SomeObject *weakSelf = self;
[self.someView doSomething:^{
        weakSelf.aVar = @"Hello!";
        [weakSelf aMethod];
    }];

and aMethod uses self

Upvotes: 3

Views: 161

Answers (2)

Stephen Darlington
Stephen Darlington

Reputation: 52565

As long as your weakSelf is declared outside your block, there is no retain cycle.

Use of objects inside the block implicitly increments the retain count. But you'd be calling aMethod on weakSelf rather than self, so the retain count is not affected.

Upvotes: 5

rckoenes
rckoenes

Reputation: 69469

You should declare the __weak to self outside of your block:

__weak SomeObject *weakSelf = self;
[self.someView doSomething:^{
     weakSelf.aVar = @"Hello!";
     [weakSelf aMethod];
}];

Else the compiler would have already retained self since it is used with the block.

Beter even is using the __block directive, because __weak is iOS 5 and higher only.

__block SomeObject *weakSelf = self;
[self.someView doSomething:^{
     weakSelf.aVar = @"Hello!";
     [weakSelf aMethod];
}];

About an other method calling self and causing retain, I've never seen this behavior. I always use the __block directive which might catch that one as well.

Upvotes: 2

Related Questions