iPhone Objective-C foreach design

前端 未结 2 1410
迷失自我
迷失自我 2021-02-19 16:20

I\'m trying to implement a design as follows:

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

相关标签:
2条回答
  • 2021-02-19 16:53

    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
      }
    }
    
    0 讨论(0)
  • 2021-02-19 17:02

    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.

    0 讨论(0)
提交回复
热议问题