Retain Cycles: Why is that such a bad thing?

前端 未结 4 810
孤街浪徒
孤街浪徒 2020-12-03 15:23

There are two Objects A and B. A creates B and retains it. B has an instance variable that points to A, retaining it. So both retain eachother. Some people say, that this st

4条回答
  •  渐次进展
    2020-12-03 15:46

    A retain cycle can be broken, if you know about it. Usually it leads to nasty bugs (memory leaks). In your example:

    A* a = [[A alloc] initAndCreateB];
    

    Now, a unnamed B instance (created by A) has a retain count of 1. Since we hold a reference to A and the anonymous B instance holds a strong reference to A, A's retain count is 2.

    Let's say, we are done using A:

    [a release];
    return 12;
    

    Now, A's retain count is 1. It will not be released, it's memory is lost. That's why retain cycles are bad.

提交回复
热议问题