State Machines in Cocoa / Objective C

| Última modificación: 14 de noviembre de 2022 | Tiempo de Lectura: 2 minutos

Algunos de nuestros reconocimientos:

Premios KeepCoding

State Machines

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:

  1. idle
  2. request-started
  3. request-sent
  4. request-timeout
  5. response-received
The graph of the possible states and transitions is:
State machine diagram_State Machines
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):

[crayon lang=”Objective C”]
-(id) initWithStates: (NSString *) firstStateName,…;
[/crayon]

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:

[crayon lang=”Objective C”]
-(void) simpleStateMachineWillMoveFromState:(NSString *) oldState
toState: (NSString *) newState;

-(void) simpleStateMachineDidMoveFromState:(NSString *) oldState
toState: (NSString *) newState;

-(BOOL) simpleStateMachineShouldMoveFromState:(NSString *) oldState
toState: (NSString *) newState;
[/crayon]

Source Code

The source code is available at GitHub.

Other state machines

A more complex implementation can be found at @alanQuatermain‘s GitHub repository.
No te pierdas ninguno de nuestros post. ¡Suscríbete!
Fernando Rodríguez

iOS Developer & Co-Fundador de KeepCoding

Posts más leídos