1

I am having difficulty trying to implement a gamestate technique which allows me to switch between different game states by storing the current state in a suitable variable.

I created NSObject *currentState which is set to the current state, but when attempting to message the [currentState method] I get the 'may not respond' error msg. (Because of the NSObject type).

I also tried creating a superclass template called Gamestate and created the individual gamestates while inheriting from the gamestate. However there is another error message relating to the fact that no methods have been implemented within the gamestate object (which is correct as I only want to implement the methods in the sub-objects).

Not sure if protocols would help me. Any suggestions on how to implement gamestate without error messages?

Thanks in advance ;)

eJm
  • 109
  • 2
  • 9

2 Answers2

0

Have a look at Creating an abstract class in Objective C.

If you declare id currentState instead of NSObject *currentState, you won't get a "may not respond" warning for [currentState method].

Community
  • 1
  • 1
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • Thanks rob, adding id has removed the error messages. Forgot to remove the '*' from *currentState at first, I will have to find out why Id wont accept pointer types. Thanks again ;) – eJm Oct 25 '11 at 12:46
  • An `id` is a pointer, so you don't need the `*`. Just think of `id` as being like `NSObject *` but with less error checking. – rob mayoff Oct 25 '11 at 18:35
0

An abstract class is a good idea, or use a protocol, if GameStates will not share much code in common (or if you can share it in a different way). That is, if you would write an abstract class, but all the methods would be abstract and there would be no code in the class, only declarations, then a protocol is probably a better match for what you're doing.

morningstar
  • 8,952
  • 6
  • 31
  • 42
  • Thanks morningstar, I thought about using a protocol, though I strive to make sure that I implement the necessary methods within the class. Are protocols mainly just to ensure that I dont forget to implement particular methods? Cheers :) – eJm Oct 25 '11 at 12:51
  • You can always use a bare id variable instead of one with a protocol. A protocol is pretty much as you say. It makes the variable strongly typed so that you must put an appropriate object in it. It allows you to check at compile time that you will not get "unrecognized selector" at runtime. – morningstar Oct 25 '11 at 16:15