简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM