Sending a message to a child from a parent

I have a Child class inherited from the Parent class. I want to send a message to the child in whom this message is implemented. So it's like calling a pure virtual function from the parent. If I send a message from the parent, I will receive a warning that the parent may not reply to this message. This is true because only the Child has its realization.

Basically, the parent will detect some actions, for example, pressing the cancel button, but each child has its own implementation of this cancel message, so I want to call from Parent onCancelso that they can do their job.

I can’t believe that using inheritance I still need to use delegates ...

+3
source share
3 answers

Checks if this method is present at run time. Therefore, even if the compiler warns you, the code can still be successful. But always check if selfthis method really defines this method.

if ([self respondsToSelector:@selector(onCancel)]) {
  [self onCancel];
}

If you want to exclude a warning, use -performSelector:.

if ([self respondsToSelector:@selector(onCancel)]) {
  [self performSelector:@selector(onCancel)];
}
+4
source

If not the one who does not understand your problem. If both the parent and child implement some code onCancel, why not just call [super onCancel]childs inside onCancel, and this will be done before the child code is executed.

+1
source

Inheritance does not eliminate the need for delegation. These are mutually exclusive aspects of OOP. It seems to me that you are really trying to implement a delegate. The classes that he delegates should not be subclasses, but discrete classes. Here you need composition, not inheritance.

0
source

All Articles