Raj
Raj

Reputation: 1139

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?

Upvotes: 9

Views: 9377

Answers (3)

Nick McConnell
Nick McConnell

Reputation: 861

This is swift, but here's an interactive demo of retain cycles in iOS: https://github.com/nickm01/RetainCycleLoggerExample

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

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.

Upvotes: 24

Simon Germain
Simon Germain

Reputation: 6844

Here's what a retain cycle is: When 2 objects keep a reference to each other and are retained, it creates a retain cycle since both objects try to retain each other, making it impossible to release.

@class classB;

@interface classA

@property (nonatomic, strong) classB *b;

@end


@class classA;

@interface classB

@property (nonatomic, strong) classA *a;

@end

To avoid retain cycles with ARC, simply declare one of them with a weak reference, like so:

@property (nonatomic, weak) classA *a;

Upvotes: 11

Related Questions