State Machines model systems that can be in any of a limited number of «conditions» (states) and moves from one to another according to a fixed set of rules. An example would be an object that represents an http connection. It might be in any of the following states:
idle
request-started
request-sent
request-timeout
response-received
The graph of the possible states and transitions is:
This is a very simplified version of Python’s HTTPConnection.
Why use state machines
State machines are a very compact way to represent a set of complex rules and conditions. They also excel at processing different inputs, such as creating a parser. State machines are commonly found in embedded devices or in any other system with very limited memory. If well implemented, a state machine is self documenting.
State Machines and UI
UIs are great candidates to be modelled with State Machines. Consider the common situation of several controls or views that should only be enabled under a certain set of conditions. With UIs getting more and more complex, State Machines are your only hope to de-spaggetify the UI code.
A simple state machine for Cocoa / Objective C
A very simple state machine implementation in Objective C. States are identified by strings and don’t carry information about what other states can the machine transition to. This behavior can be added by the machine’s delegate.
Initialization
The machine is initialized with a list of states (NSStrings):
initWithStates: is a variadic method that accepts a list of strings of variable length. The list must end with nil.
Delegate
The delegate will be notified of state changes and can also prevent a state change. To conform to the protocol, a class should implement any of the following @optional methods: