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:
Esta web utiliza cookies para que podamos ofrecerte la mejor experiencia de usuario posible. La información de las cookies se almacena en tu navegador y realiza funciones tales como reconocerte cuando vuelves a nuestra web o ayudar a nuestro equipo a comprender qué secciones de la web encuentras más interesantes y útiles.
Cookies estrictamente necesarias
Las cookies estrictamente necesarias tiene que activarse siempre para que podamos guardar tus preferencias de ajustes de cookies.
Si desactivas esta cookie no podremos guardar tus preferencias. Esto significa que cada vez que visites esta web tendrás que activar o desactivar las cookies de nuevo.
Cookies de terceros
Esta web utiliza Google Analytics para recopilar información anónima tal como el número de visitantes del sitio, o las páginas más populares.
Dejar esta cookie activa nos permite mejorar nuestra web.
¡Por favor, activa primero las cookies estrictamente necesarias para que podamos guardar tus preferencias!