简体   繁体   English

作为iVar的weakSelf

[英]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. 我知道以下事实:您应该在块中使用weakSelf,这样可能会使其生存下来以避免保留内存周期。 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. 这简化了,但是我想知道为什么我不能在viewController上使用ivar。

@interface YDViewController : UIViewController
{
    __weak id _weakSelf;
}

and then use this iVar 然后使用这个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] . 引起这个想法的问题是[_weakSelf something][_weakSelf something][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. 因此,即使您尝试使用弱引用,您最终还是要使用强引用来获取弱引用并捕获两者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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