views:

45

answers:

3

I have class Child inherited from class Parent. What I want is to send message to child, which has implementation of that message. So it's like calling pure virtual function from parent. If I send message now from Parent I'll get warning that Parent may not respond to this message. It is true, because only Child has implementation of it.

Basically Parent will detect some action like tap on cancel button, but each child has its own implementation of that cancel message, so I want to call from Parent onCancel to let them do their job.

Can't believe that using inheritance I still have to use delegates...

+3  A: 

Whether the method is present is checked at runtime. Therefore, even if the compiler warns you, the code could still succeed. But always check if self really defines that method first.

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

If you want to eliminate the warning, use -performSelector:.

if ([self respondsToSelector:@selector(onCancel)]) {
  [self performSelector:@selector(onCancel)];
}
KennyTM
You might be able to eliminate the warning by casting self to type `id` which will result in marginally quicker execution than using performSelector:
JeremyP
A: 

Inheritence does not remove the need for delegation. Those are mutually exclusive aspects of OOP. It sounds to me as though your are indeed trying to implement a delegator. The classes that it delegates to shouldn't be subclasses of it, but discrete classes. What you need here is composition, not inheritence.

Rich
+1  A: 

Unless am the one who's not understanding your problem. If both parent and child implement some onCancel code why not just call [super onCancel] inside the childs onCancel and this will be executed before the child's code is executed.

domino