Swift strong reference cycles with arrays

213 views Asked by At

If I have a class A which has a variable x which is an array of class B, and class B which always has a variable y parent of class A, how do I set up to avoid strong reference cycles. I get an error if I put

class A {
weak var x = [B] 
...}

(even if I make it [B]? ) and it seems the wrong way around to put

class B {
weak var y = A
...}

as class B should always have a 'parent' class A.

I imagine this is a standard set up so wondering the normal pattern. Any help much appreciated.

1

There are 1 answers

0
Rob Napier On BEST ANSWER

If B will always have a parent, and the parent will ensure that it cannot go away before its children, then you can use unowned rather than weak. That said, unowned is somewhat dangerous because if you are wrong, it will crash.

If you want to be a bit safer (or you can't promise that the children will always be destroyed before their parents), then the correct pattern is a weak reference to the parent.

The key is in the phrase "should always have a 'parent'." If you mean should, then use weak. If you mean must then use unowned.

While it is possible to create "weak arrays," this is not a good use of that. Parents in your example "own" (have a strong reference to and keep alive) their children. Children in this system do not "own" their parents, and so shouldn't have a strong reference.