NSTimer: The Poor Man’s Threading – Code Snapshot

    July 23rd, 2009 Posted by: - posted under:Snippets

    Introduction

    Hey guys. So usually the posts we put up here involve screencasts and presentations, but we are going to start also posting small less time consuming pieces for the site. Today I bring to you a small project involving NSTimers. Today we are going to build an app that represents a horse race. We will create a view with 6 small UIView squares with a blue background at the bottom of the screen, we will use a timer to move a random one of them forward a random amount of distance. Let’s get started!

    Picture 16

    Source

    You can get the source here: NSTimerDemo

    Steps

    Step 1

    Create a view based application in xCode. Call it whatever.

    Step 2

    In your view controller class header file add:

    NSTimer *myTimer;

    Step 3

    In your view controller class, uncomment out the viewDidLoad method and fill in the following code:

    - (void)viewDidLoad
    {
          [super viewDidLoad];
     
          CGRect workingFrame;
          workingFrame.origin.x = 15;
          workingFrame.origin.y = 400;
          workingFrame.size.width = 40;
          workingFrame.size.height = 40;
     
          for(int i = 0; i < 6; i++)
          {
               UIView *myView = [[UIView alloc] initWithFrame:workingFrame];
               [myView setTag:i];
               [myView setBackgroundColor:[UIColor blueColor]];
     
               workingFrame.origin.x = workingFrame.origin.x + workingFrame.size.width + 10;
               [self.view addSubview:myView];
          }
     
          myTimer = [NSTimer scheduledTimerWithTimeInterval:.1 target:self selector:@selector(moveACar) userInfo:nil repeats:YES];
      }

    Step 4

    In your view controller class, add the following method:

    -(void)moveACar
    {
          int r = rand() % 6;
          NSLog(@"My number is %d", r);
     
          for(UIView *aView in [self.view subviews])
          {
               if([aView tag] == r)
               {
                    int movement = rand() % 100;
                    CGRect workingFrame = aView.frame;
                    workingFrame.origin.y = workingFrame.origin.y - movement;
     
                    [UIView beginAnimations:nil context:NULL];
                    [UIView setAnimationDuration:.2];
                    [aView setFrame:workingFrame];
                    [UIView commitAnimations];
     
                    if(workingFrame.origin.y < 0)
                    {
                        [myTimer invalidate];
                    }
               }
          }
    }

    Conclusion

    So that is it. Timers are really cool and come in handy for all sorts of small problems in a project. Happy coding.