I have a container view controller with 3 child UIViewController subclasses (added with addChildViewController). I want one of my child view controllers to do something when something is dropped from my container view controller onto it. I’m having trouble grasping how this communication should happen. If I try making a delegate, I get an error in my child view controller because I would both subclasses to import each other.
I have a container view controller with 3 child UIViewController subclasses (added with addChildViewController).
Share
It sounds like you’re having a problem compiling your app because of mutual .h files
importingeach other, right?There’s a number of ways to handle this. If you want to stay with a
delegatepattern, you could simply rewrite the header to avoid the#importin one of the .h files:ParentViewController.h:
ChildViewController.h
ChildViewController.m
This should avoid the circular dependency that keeps your app from compiling.
Now, although the above works, I might choose another solution, for the sake of cleanliness. Use a
protocol. The parent can implement the protocol and then the child only needs to have a delegate that implements the protocol:In MyProtocol.h:
Then in ChildViewController.h
And in ChildViewController.m:
Or, you could avoid using delegates altogether, and communicate between the controllers using
NSNotificationCenter, which decouples them a bit, and avoids your compiler circularity (bidirectional dependency).Here are the Apple docs on NSNotificationCenter