SpaceDog SpaceDog - 7 months ago 48
iOS Question

Weak references conundrum

Suppose I want to create a weak reference so it will not be retained by a block. So I have a property:

@property (nonatomic, strong) MyClass *myObject;

and I do this:

__weak typeof(self.myObject) myObjectWeak = self.myObject;

void (^doSomething)() = ^void() {
[myObjectWeak doSomething];

but what about this:

__weak typeof(self) selfWeak = self;

void (^doSomething)() = ^void() {
[selfWeak.myObject doSomething];

Will this produce the same effect? I mean having a weak reference to myObject inside the block? I suspect it is not, but I just need to confirm.

Rob Rob

Yes, using selfWeak in that last example is sufficient to break the strong reference cycle. Don't worry about the fact that you reference its properties in there.