Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retain Cycle in ARC

I have never worked on non ARC based project. I just came across a zombie on my ARC based project. I found it was because of retain cycle.I am just wondering what is a retain cycle.Can

Could you give me an example for retain cycle?

like image 492
Raj Avatar asked Oct 09 '12 14:10

Raj


People also ask

What is the retain cycle?

— in order to deallocate an object from memory, its ARC value must be zero. However, when some two object refers each other via strong references, they prevent the compiler from deallocating either object because their ARC value would always be 1. That is called a retain cycle.

What is retain cycle in Android?

In our app, a home has to have a property owner and a property owner has to have a home. What we've done with this code is created a retain cycle. The Property Owner will always remain in memory because it will always have a reference count of at least 1, and the Home will do the same.

How do you retain retaining cycle?

There are two possible solutions: 1) Use weak pointer to parent , i.e a child should be using weak reference to parent, which is not retained. 2) Use "close" methods to break retain cycles.

What's retain cycle how you can avoid?

Avoiding retain cycles rule #1: An object must never retain its parent. The first rule to avoid retain cycles is that an object must never retain its parent. This changes the previous diagram to the following: This is the easy case: an object should never retain its parent when it makes a pointer to the parent.


1 Answers

A retain cycle is a situation when object A retains object B, and object B retains object A at the same time*. Here is an example:

@class Child;
@interface Parent : NSObject {
    Child *child; // Instance variables are implicitly __strong
}
@end
@interface Child : NSObject {
    Parent *parent;
}
@end

You can fix a retain cycle in ARC by using __weak variables or weak properties for your "back links", i.e. links to direct or indirect parents in an object hierarchy:

@class Child;
@interface Parent : NSObject {
    Child *child;
}
@end
@interface Child : NSObject {
    __weak Parent *parent;
}
@end


* This is the most primitive form of a retain cycle; there may be a long chain of objects that retain each other in a circle.
like image 93
Sergey Kalinichenko Avatar answered Nov 15 '22 21:11

Sergey Kalinichenko