title: How to Make a Basic Finite State Machine in Objective-C
body: <p>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 containing pages of if-then statements. The complexity, non-readability, and difficulty of adding/changing features lead me to attempt a more formal solution like this. </p>
  
  <p>In the context of the application, the state of the timer determines some complex interactions with NSManagedObjects, Core Data, and so forth. I have left all that functionality out for now, in an attempt to get a clear view of the FSM code. </p>
  
  <p>The trouble is, I cannot find any examples of this sort of code in Obj-C, and I am not so confident about how I have translated it from the C++ example code I was using. (I don't know C++ at all, so there is some guessing involved.) I am basing this version of a state pattern design on this article: <a href="http://www.ai-junkie.com/architecture/state_driven/tut_state1.html" rel="nofollow noreferrer">http://www.ai-junkie.com/architecture/state_driven/tut_state1.html</a>. I'm not making a game, but this article outlines concepts that work for what I'm doing. </p>
  
  <p>In order to create the code (posted below), I had to learn a lot of new concepts, including obj-c protocols, and so forth. Because these are new to me, as is the state design pattern, I'm hoping for some feedback about this implementation. Is this how you work with protocol objects effectively in obj-c? </p>
  
  <p>Here is the protocol:</p>
  
  <pre><code>@class Timer;
  @protocol TimerState 
  
  -(void) enterTimerState:(Timer*)timer;
  -(void) executeTimerState:(Timer*)timer;
  -(void) exitTimerState:(Timer*)timer;
  
  @end
  </code></pre>
  
  <p>Here is the Timer object (in its most stripped down form) header file:</p>
  
  <pre><code>@interface Timer : NSObject
  {       
      id&lt;TimerState&gt; currentTimerState;
      NSTimer *secondTimer;
      id &lt;TimerViewDelegate&gt; viewDelegate;
  
      id&lt;TimerState&gt; setupState;
      id&lt;TimerState&gt; runState;
      id&lt;TimerState&gt; pauseState;
      id&lt;TimerState&gt; resumeState;
      id&lt;TimerState&gt; finishState;
  }
  
  @property (nonatomic, retain) id&lt;TimerState&gt; currentTimerState;
  @property (nonatomic, retain) NSTimer *secondTimer;
  @property (assign) id &lt;TimerViewDelegate&gt; viewDelegate;
  
  @property (nonatomic, retain) id&lt;TimerState&gt; setupState;
  @property (nonatomic, retain) id&lt;TimerState&gt; runState;
  @property (nonatomic, retain) id&lt;TimerState&gt; pauseState;
  @property (nonatomic, retain) id&lt;TimerState&gt; resumeState;
  @property (nonatomic, retain) id&lt;TimerState&gt; finishState;
  
  -(void)stopTimer;
  -(void)changeState:(id&lt;TimerState&gt;) timerState;
  -(void)executeState:(id&lt;TimerState&gt;) timerState;
  -(void) setupTimer:(id&lt;TimerState&gt;) timerState;
  </code></pre>
  
  <p>And the Timer Object implementation:</p>
  
  <pre><code>#import "Timer.h"
  #import "TimerState.h"
  #import "Setup_TS.h"
  #import "Run_TS.h"
  #import "Pause_TS.h"
  #import "Resume_TS.h"
  #import "Finish_TS.h"
  
  
  @implementation Timer
  
  @synthesize currentTimerState;
  @synthesize viewDelegate;
  @synthesize secondTimer;
  
  @synthesize setupState, runState, pauseState, resumeState, finishState;
  
  -(id)init
  {
      if (self = [super init])
      {
          id&lt;TimerState&gt;  s = [[Setup_TS alloc] init];
          self.setupState = s;
          //[s release];
  
          id&lt;TimerState&gt; r = [[Run_TS alloc] init];
          self.runState = r;
          //[r release];
  
          id&lt;TimerState&gt; p = [[Pause_TS alloc] init];
          self.pauseState = p;
          //[p release];
  
          id&lt;TimerState&gt; rs = [[Resume_TS alloc] init];
          self.resumeState = rs;
          //[rs release];
  
          id&lt;TimerState&gt; f = [[Finish_TS alloc] init];
          self.finishState = f;
          //[f release];  
      }
      return self;
  }
  
  -(void)changeState:(id&lt;TimerState&gt;) newState{
      if (newState != nil)
      {
          [self.currentTimerState exitTimerState:self];
          self.currentTimerState = newState;
          [self.currentTimerState enterTimerState:self];
          [self executeState:self.currentTimerState];
      }
  }
  
  -(void)executeState:(id&lt;TimerState&gt;) timerState
  {
      [self.currentTimerState executeTimerState:self];    
  }
  
  -(void) setupTimer:(id&lt;TimerState&gt;) timerState
  {
      if ([timerState isKindOfClass:[Run_TS class]])
      {
          secondTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(currentTime) userInfo:nil repeats:YES];
      }
      else if ([timerState isKindOfClass:[Resume_TS class]])
      {
          secondTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(currentTime) userInfo:nil repeats:YES];
      }
  }
  
  -(void) stopTimer
  {   
      [secondTimer invalidate];
  }
  
  -(void)currentTime
  {   
      //This is just to see it working. Not formatted properly or anything.
      NSString *text = [NSString stringWithFormat:@"%@", [NSDate date]];
      if (self.viewDelegate != NULL &amp;&amp; [self.viewDelegate respondsToSelector:@selector(updateLabel:)])
      {
          [self.viewDelegate updateLabel:text];
      }
  }
  //TODO: releases here
  - (void)dealloc
  {
      [super dealloc];
  }
  
  @end
  </code></pre>
  
  <p>Don't worry that there are missing things in this class. It doesn't do anything interesting yet. I'm currently just struggling with getting the syntax correct. Currently it compiles (and works) but the isKindOfClass method calls cause compiler warnings (method is not found in protocol). I'm not really sure that I want to use isKindOfClass anyway. I was thinking of giving each <code>id&lt;TimerState&gt;</code> object a name string and using that instead. </p>
  
  <p>On another note: all those <code>id&lt;TimerState&gt;</code> declarations were originally TimerState * declarations. It seemed to make sense to retain them as properties. Not sure if it makes sense with <code>id&lt;TimerState&gt;</code>'s. </p>
  
  <p>Here is an example of one of the state classes: </p>
  
  <pre><code>#import "TimerState.h"
  
  
  @interface Setup_TS : NSObject &lt;TimerState&gt;{
  
  }
  
  @end
  
  #import "Setup_TS.h"
  #import "Timer.h"
  
  @implementation Setup_TS
  
  -(void) enterTimerState:(Timer*)timer{
      NSLog(@"SETUP: entering state");
  }
  -(void) executeTimerState:(Timer*)timer{
      NSLog(@"SETUP: executing state");
  }
  -(void) exitTimerState:(Timer*)timer{
      NSLog(@"SETUP: exiting state");
  }
  
  @end
  </code></pre>
  
  <p>Again, so far it doesn't do anything except announce that what phase (or sub-state) it's in. But that's not the point. </p>
  
  <p>What I'm hoping to learn here is whether this architecture is composed correctly in the obj-c language. One specific problem I'm encountering is the creation of the id objects in the timer's init function. As you can see, I commented out the releases, because they were causing a "release not found in protocol" warning. I wasn't sure how to handle that. </p>
  
  <p>What I don't need is comments about this code being overkill or meaningless formalism, or whatever. It's worth me learning this even it those ideas are true. If it helps, think of it as a theoretical design for an FSM in obj-c. </p>
  
  <p>Thank you in advance for any helpful comments. </p>
  
  <p>(this didn't help too much: <a href="https://stackoverflow.com/questions/1110572/finite-state-machine-in-objective-c">Finite State Machine in Objective-C</a>)</p>