【问题标题】:weakSelf as an iVarweakSelf 作为 iVar
【发布时间】:2013-10-01 23:32:51
【问题描述】:

我知道你应该在 block 中使用 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];
}

有什么想法吗?

【问题讨论】:

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


    【解决方案1】:

    这个想法的问题在于[_weakSelf something] 在底层与[self->_weakSelf something] 完全相同。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      • 2012-02-23
      • 1970-01-01
      • 2019-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多