A common pattern would be to have the child
as a property of the parent
, and have the parent
be a delegate of the child
. The first thing you need to do is make your own protocol.
// MyProtocol.h
- (void)heyParentSomethingHappened:(Something)something;
Next, make the child
a property of the parent
so they can talk through delegation.
// ParentVC.m
@interface ParentVC()
@property (nonatomic) ChildVC *child
@end
Now that the parent
has the child
as a property, they need some way to talk. This is where the delegation comes in. Have the parent conform to MyProtocol
.
// ParentVC.h
@interface ParentVC : UIViewController <MyProtocol>
Now that the parent
conforms to your special protocol, have the child
make it a delegate.
//ChildVC.h
@interface ChildVC : UIViewController
@property (nonatomic) id <MyProtocol> delegate.
@end
Now that the child
has the delegate
property, set it to the parent and you are good to go.
// ParentVC.m
- (id)init {
// do your init
self.child.delegate = self // both (child.delegate, self) conform to <MyProtocol>, so no type mismatch.
}
Now when your child
needs to alert your parent
of something, they have a formal way of talking through the protocol + delegation.
// ChildVC.m
- (void)someFunc {
[self.delegate heyParentSomethingHappend:[Something new]];
}
Remember to always include the protocol file when using it.