ios - 作为iVar的weakSelf

标签 ios objective-c memory-leaks weak-references

我知道以下事实:您应该在块中使用weakSelf,这样可能会生存下来,从而避免保留内存周期。
喜欢:

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

但是我试图找到一种通用的方式。我可以使用像这样的宏:
#define Weakify(o) __weak __typeof__((__typeof__(o))o)
#define WeakifySelf(o) Weakify(self) o = self;

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

这简化了,但是我想知道为什么我不能在viewController上使用ivar。
@interface YDViewController : UIViewController
{
    __weak id _weakSelf;
}

然后使用这个iVar
self.block = ^{
    [_weakSelf something];
}

任何想法?

最佳答案

引起这个想法的问题是[_weakSelf something]在幕后与[self->_weakSelf something]完全相同。

因此,即使您尝试使用弱引用,您最终还是会使用强引用来获取弱引用并捕获两者。

关于ios - 作为iVar的weakSelf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19127726/

相关文章:

ios - 获取物体背后的颜色

C++ - 内存泄漏 - 指向结构的指针

iphone - 如何使用 UIAlertView 关闭模态视图 Controller ?

Objective-C 中间对象优化

ios - 如何将 UIImageview 从 A 点移动到 B 点一定程度

objective-c - 为什么我的 for 循环泄漏?

swift - 克隆节点时 SceneKit 泄漏

objective-c - "Incompatible pointer to integer conversion initializing ' int ' with an expression of type ' NSNumber * '"

ios - 不同类型的 Controller 如何连接?

ios - SwiftUI:避免使用 MKMapView+UIViewRepresentable 在 TabView 中重新创建/重新渲染 View