简体   繁体   中英

Can a child view controller be the delegate of its parent view controller?

Lets say there are two classes, class A and class B. Class B is a child view controller of A.

protocol ClassADelegate: class{
     functions
}
class A {
     code
     add B as child view controller
}


protocol ClassBDelegate: class{
     functions
}
class B {
     code
}

Considering that class A is the parent view controller of B, My question is if class A is a delegate of class B and class B is a delegate of class A, does that create an ownership cycle? Is this bad practice?

Delegates in Cocoa are stored as weak references. Weak references can't keep objects alive the way strong references do, thus you have no risk of strong reference cycles.

However, I can't think of a situation in which this would make sense. It's not really a delegate pattern anymore, it's just 2 objects arbitrarily messaging each other.

The parent should be the child's delegate.

The parent, if it needs to tell the child something, should just invoke methods.

if class A is a delegate of class B and class B is a delegate of class A, does that create an ownership cycle? Is this bad practice?

It doesn't necessarily produce a reference cycle. Normally, an object doesn't retain its delegate. As to whether it's bad practice, that depends. It's unusual, in that you'd normally expect that a delegate would have a lifetime at least as long as the object that it's delegating for, while you'd expect a child view controller to have a shorter lifetime than its parent. Without knowing more about your intended design, it's impossible to say for sure.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM