How to Make a Basic Finite State Machine in Objective-C

后端 未结 5 2006
长发绾君心
长发绾君心 2020-12-07 17:45

I am attempting to build an FSM to control a timer in (iphone sdk) objective c. I felt it was a necessary step, because I was otherwise ending up with nasty spaghetti code c

相关标签:
5条回答
  • 2020-12-07 18:19

    I am rather new at Objective-C, but I would suggest that you look at straight ANSI C implementation for the State Machine.

    Just because you're using Cocoa doesn't mean you have to use Objective-C messages here.

    In ANSI C, a state machine implementation can be very straightforward and readable.

    My last implementation in C of a FSM specified #define STATE_x or enumerate types for the states and had a table of pointers to functions to execute each state.

    0 讨论(0)
  • 2020-12-07 18:28

    If you want a very simple, Objective-C implementation of a State Machine I've just released TransitionKit, which provides a well designed API for implementing state machines. It's thoroughly tested, well documented, very easy to use, and doesn't require any code generation or external tools.

    0 讨论(0)
  • 2020-12-07 18:29

    I suggest using State Machine Compiler, it will output Objective-C code. I have had good success in Java and Python using this.

    You shouldn't be writing state machine code by hand, you should be using something to generate the code for you. SMC will generate clean clear code you can then look at if you want to learn from it, or you can just use it and be done with it.

    0 讨论(0)
  • 2020-12-07 18:40

    I'd suggest checking out Statec it's got a nice little dsl for doing FSM and outputs ObjC code. It's sort of like mogenerator for state machines.

    0 讨论(0)
  • 2020-12-07 18:44

    When you use a protocol as a type-modifier, you can provide a comma-separated list of protocols. So all you need to do to get rid of the compiler warning is add NSObject to the protocol list like so:

    - (void)setupTimer:(id<TimerState,NSObject>) timerState {
    
        // Create scheduled timers, etc...
    }
    
    0 讨论(0)
提交回复
热议问题