I've been reading up more on retain cycles all day and I'm starting to confuse myself. So I just wanted to check a couple of things. (Just for clarification, I'm using ARC)
So let's say I have MyFirstClass
. MyFirstClass
has an strongly pointed (by default) instance variable to MyChildClass
:
MyChildClass *_child;
MyFirstClass
also has a getter (publicly available in the .h) like so:
-(MyChildClass *)child
{
return _child;
}
Now let's say I have another class entirely, MySecondClass
. MySecondClass
has a weak instance variable pointing to MyFirstClass
like so:
__weak MyFirstClass *_firstClass;
There is a parent class that holds both MyFirstClass
and MySecondClass
so MySecondClass
just has a weak reference to MyFirstClass
so it doesn't stop the parent class from releasing it when it wants to.
MySecondClass
also has it's own child class, strongly referenced with an instance variable too:
MySecondChildClass *_secondClassChild;
MySecondChildClass
wants to reference MyFirstClass
's MyChildClass
object.
So I guess I use a weak pointer here too, within MySecondChildClass
:
__weak MyChildClass *_firstClassChild;
It has a custom init to set this:
-(id)initWithFirstClassChild:(MyChildClass *)firstClassChild
{
if(self = [super init]){
_firstClassChild = firstClassChild;
}
}
Finally, there is a method in MySecondClass
that creates MySecondChildClass
:
-(void)setupChild
{
_secondClassChild = [[MySecondChildClass alloc] initWithFirstClassChild:_firstClass.child];
}
Is this all correct? I'm 90% sure that's all fine but I'm getting confused.
What about when I'm using _firstClass.child
, does that create a strong pointer to it? Should I be referencing __weak
somewhere in that method call? How about during MySecondChildClass
's init? It has a temporary pointer to MyChildClass
before it sets the instance variable, does that create a strong pointer I should worry about?
Any clarification would be great.
I don't think you need any weak references here.
I'm calling these objects P, A, A', B, and B' where:
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"
So then your picture looks like this, if I read your question correctly:
/----> A ----> A'
/ ^ ^
P | |
\ | |
\----> B ----> B'
If that picture matches what you wrote, then there is no retain cycle there and you shouldn't therefore need any of those references to be weak.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.