Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

What makes a finite state machine?

A finite state machine is a mathematical abstraction used to design algorithms. In simpler terms, a state machine will read a series of inputs. When it reads an input, it will switch to a different state. Each state specifies which state to switch to, for a given input.

What is the formula for machine function in finite state machine?

A FSM M is defined by a tuple (Q, q0, δ, λ, X, Y) in which Q is a finite set of states, qo∈ Q is the initial state, δ is the state transfer function, λ is the output function, X is the finite input alphabet; and Y the finite output alphabet.


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.


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...
}

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.


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.


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.