ios - 在弱指针上调用 getter 并将其传递给方法时保留循环可能性

标签 ios memory-management memory-leaks automatic-ref-counting retain-cycle

我一整天都在阅读更多关于保留周期的内容,我开始对自己感到困惑。所以我只想检查几件事。 (为了澄清起见,我使用的是 ARC)

假设我有 MyFirstClassMyFirstClass 有一个强指向(默认)实例变量到 MyChildClass:

MyChildClass *_child;

MyFirstClass 还有一个 getter(在 .h 中公开可用),如下所示:

-(MyChildClass *)child
{
    return _child;
}

现在假设我有另一个完整的类,MySecondClassMySecondClass 有一个指向 MyFirstClass 的弱实例变量,如下所示:

__weak MyFirstClass *_firstClass;

有一个父类同时包含 MyFirstClassMySecondClass 所以 MySecondClass 只是对 MyFirstClass 的弱引用> 所以它不会阻止父类在需要时释放它。

MySecondClass 也有它自己的子类,也被实例变量强引用:

MySecondChildClass *_secondClassChild;

MySecondChildClass 想要引用 MyFirstClassMyChildClass 对象。

所以我想我在这里也使用了一个弱指针,在 MySecondChildClass 中:

__weak MyChildClass *_firstClassChild;

它有一个自定义的 init 来设置它:

-(id)initWithFirstClassChild:(MyChildClass *)firstClassChild
{
    if(self = [super init]){
        _firstClassChild = firstClassChild;
    }
}

最后,MySecondClass 中有一个创建MySecondChildClass 的方法:

-(void)setupChild
{
    _secondClassChild = [[MySecondChildClass alloc] initWithFirstClassChild:_firstClass.child];
}

这一切都正确吗?我 90% 确定这一切都很好,但我感到困惑。

当我使用 _firstClass.child 时,会创建指向它的强指针吗?我应该在该方法调用的某处引用 __weak 吗?在 MySecondChildClass 的初始化期间怎么样?在设置实例变量之前,它有一个指向 MyChildClass 的临时指针,这是否会创建一个我应该担心的强指针?

任何澄清都会很好。

最佳答案

我认为您在这里不需要任何弱引用。

我将这些对象称为 P、A、A'、B 和 B',其中:

P is an instance of your "Parent Class"
A is an instance of "MyFirstClass"
A' is an instance of "MyChildClass"
B is an instance of "MySecondClass"
B' is an instance of "MySecondChildClass"

那么你的图片看起来像这样,如果我没看错你的问题:

  /----> A ----> A'
 /       ^       ^
P        |       |
 \       |       |
  \----> B ----> B'

如果该图片与您所写的相匹配,那么那里就没有保留周期,因此您不应该需要任何弱引用。

关于ios - 在弱指针上调用 getter 并将其传递给方法时保留循环可能性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14764241/

相关文章:

ios - 在 iOS 中将 ExtAudioFileRef 类型转换为 AudioFileID 类型

ios - swift 中包含 AWSAPIGatewayResponse 的单元测试方法

c++ - 使用变量定义数组大小和使用新运算符 c++ 有什么区别?

与 calloc 与 malloc 相关的 C 教程问题

c - C中当前进程的内存使用情况

c - MPIR 编码错误

C++ - 使用 _CrtDumpMemoryLeaks() 进行内存泄漏测试 - 不输出行号

ios - 我可以在 JSQMessagesViewController 单元格中为 textView.text 使用 NSAttributedString 吗?

ios - 从某些 UISegmentedControl 索引获取帧?

Android:查找内存泄漏的工具?