Is this a retention cycle?

I usually get a warning when I call something on myself in a block I saved:

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

      

I need 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, it will keep the loop persisting, even though I don't get a warning? I say this:

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

      

and aMethod uses self

+3


source to share


2 answers


As long as yours is weakSelf

declared outside of your block , the save cycle is not saved.



Using objects inside a block implicitly increases the number of holds. But you would type aMethod

on weakSelf

, not self

, so the save value has no effect.

+5


source


You must declare __weak

to self

outside of your block:

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

      

Otherwise, the compiler would have saved itself already, since it is being used with a block.



Beter even uses the directive __block

because __weak

only iOS 5 and up.

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

      

On another method calling itself and causing a save, I've never seen this behavior. I always use a directive __block

which can catch it too.

+2


source







All Articles