views:

267

answers:

2

I'm trying to implement a design as follows:

Touch class : acts as an interface, several classes inherit from it MoveTouch class inherits JumpTouch class inherits InterfaceTouch class inherits

Then I want to have a list of Touch objects. I then want to be able to strip out all the MoveTouch objects ONLY (not the other ones), and then all the JumpTouch objects separately, etc., out of this big list. Unfortunately, "for (MoveTouch* t in touches)" does not do what I want; everything in the entire list gets acted upon.

Help would be appreciated.

+9  A: 

You need to test for the class type:

for (Touch *t in touches) {
  if ([t isKindOfClass:[MoveTouch class]]) {
    MoveTouch *mt = (MoveTouch *)t;
    // do what you want with mt
  }
}
Louis Gerbarg
A: 

I'm not an Objective C programmer.

In your case, I think you need to go through your list with that "for (Touch* in touches)" and in the body figure out if that object is either a MoveTouch or a JumpTouch and so forth.

But the idea of polymorphism is that you don't do this. You don't sort 'm out during your loop. The action that you want to perform should be defined in the interface, and each descendant class implements a different implementation for that action. That's what polymorphism is all about.

Dave Van den Eynde
... which means you would do something like call [t update] and then each item would decide what to do at an update cycle. But that's not universal. There are plenty of times when you have a message you want to send to one class, and not another.
Kenny Winker
not universal, but does tend to smell, in my opinion. Especially when you indicate that you're designing the classes themselves as well.
Dave Van den Eynde
I'm actually not doing polymorphism with this. My basic want was for a way to separate different kinds of touches. The kind of touch (Move, Jump, Interface, etc.) can be decided immediately upon its creation, which happens within "touchesBegan". From then on, it's much easier to separate the functionality of what happens when you MOVE that touch or END that touch, etc. I guess maybe inheritance is a little fancy for this? Maybe just a simple enum would work?
Scott
Why yes, if you don't want polymorphism then inheritance is a bit overkill. A simple enum would avoid the whole runtime type checking, which is probably a lot less efficient.
Dave Van den Eynde