简体   繁体   中英

weakSelf as an iVar

I'm aware of the fact that you should use weakSelf in block that may survive yourself to avoid retain memory cycle. like:

__weak id weakSelf = self;
self.block = ^{
    [weakSelf something];
}

But I'm trying to find a generic way. I could use a macro like:

#define Weakify(o) __weak __typeof__((__typeof__(o))o)
#define WeakifySelf(o) Weakify(self) o = self;

WeakifySelf(weakSelf)
self.block = ^{
    [weakSelf something];
}

Which simplify, but I wonder why I can't use an ivar on my viewController.

@interface YDViewController : UIViewController
{
    __weak id _weakSelf;
}

and then use this iVar

self.block = ^{
    [_weakSelf something];
}

Any idea?

The issue that sinks this idea is that [_weakSelf something] is, under the hood, exactly the same as [self->_weakSelf something] .

So even though you're trying to use a weak reference, you end up using the strong reference to get to the weak reference and capturing both.

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