Subscribe ( RSS )

iPhone Programming Tutorials


 

NSTimer: The Poor Man’s Threading – Code Snapshot

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:

Advertisement

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.

 

23 Responses

Techy Says:

July 23rd, 2009 at 1:03 pm

Very Cool! Do you think that you guys could make a tutorial on how to add screenshots to your app?

Bergamot Says:

July 23rd, 2009 at 1:24 pm

Techy: Hold the home button, and press the sleep button.

Or take a screenshot of the simulator.

Techy Says:

July 23rd, 2009 at 2:07 pm

I know that, I mean making it so it takes a screenshot by pressing a button within the app…

kenny Says:

July 23rd, 2009 at 6:49 pm

UIGraphicsBeginImageContext(self.view.bounds.size);

[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

you must also #import

iPhone Objective-C Programming NSTimer | iPhone Development Tutorials and Tips Says:

July 24th, 2009 at 12:22 am

[...] found this good example here on timers: NSTimer the Poor Man’s Threading Code Snapshot While it’s foolishly titled a Poor Man’s Threading which may give you the impression [...]

Rein Hillmann Says:

July 24th, 2009 at 12:23 am

Instead of looping through the views to get to the appropriate tag, why not do the following?:

UIView *aView = [self.view viewWithTag:r];

Also, you might want to start your tags with 1 instead of 0. The default tag value is 0 and, even though it works in this case where you have no other views, it will clash if you add more views that you don’t explicitly tag.

Maniacdev Says:

July 24th, 2009 at 12:30 am

Nice example. Just not sure about calling them a poor man’s thread though.

The only problem I have with NSTimer’s is that they can be innacurate.

Mikko K Says:

July 26th, 2009 at 4:59 am

Nice tutorial! I prefer use arc4random() instead of rand(). By using rand() you will get the same result every time. Arc4random() is a real random generator :)
Right?

Picoman Says:

July 26th, 2009 at 5:25 am

Hi,

Great stuff!

Just one thing though.
The two lines of code below produce four errors and i am unsure what the &lt is doing.

for(int i = 0; i < 6; i++)

if(workingFrame.origin.y < 0)

I think they should read:

for(int i = 0; i < 6; i++)

if(workingFrame.origin.y < 0)

Thank You

Alex

Picoman Says:

July 26th, 2009 at 5:27 am

Well is guess < gets translated to & l t on this site. Ignore previous post. :-S

max Says:

July 26th, 2009 at 3:44 pm

im getting a warning NSTimer may not respond to + scheduledTimerWithTimeInterval…

Programmatically Getting a Screencapture of any UIView | iCodeBlog Says:

July 27th, 2009 at 11:42 am

[...] guys. This post is in response to a comment made in my last post about NSTimers. Techy asked if we could do a post on how to take screenshots programmatically using the iPhone [...]

Sylvain Says:

August 18th, 2009 at 8:54 am

Maybe a silly question (noob inside :) ), but myView are not released ? It should be ?

rully lukita Says:

August 18th, 2009 at 12:57 pm

I just add random to UIView squares with arc4random(),
you just add
int xm = (arc4random() % 6)+1;
NSLog(@”My XM number is %d”, xm);

for(int i = 0; i < xm; i++)
{
UIView *myView = [[UIView alloc] initWithFrame:workingFrame];
bla..bla….

Picoman Says:

August 31st, 2009 at 7:01 am

Is there a way to animate the squares? For example pass through an array of 6 .pngs to create animations? Maybe change all the blue squares to little spiders with moving legs?

ephellulk Says:

September 9th, 2009 at 8:49 am

Центр Кровли — это современная компания, специализпрующаяся на реализации кровельных и отделочных материалов, Мы осуществляем монтаж кровли из металлочерепицфы. Являясь дистрибьютором многих производителей, мы можем гарантировать качество кровельных работ . Мы имеем сооответствующую лицензию на мнотаж кровли . Компания оказывавет полный комплекс услуг для реализации намеченных планов в одном месте: изготовление мягкой кровли – все это вы можете смело доверить нам.
Мы работаем уже более 10 лет на рынке кровельных материалов, и за это время компания доказала свою ответственность. Мы стремимся создать более удобные условия работы для клиентов, поэтому наши представительства находятяс в городах Пенза, Саратов Саранск и Москва. С 2009 года открыт филиал Центра Кровли в Московской области с собственным произвдсотвом металлочерепицы профиля «СуперМонтеррей» с полимерным покрытием, а также комплектующих элементов

arenda-n Says:

September 28th, 2009 at 4:14 am

Где все сообщения и темы которые я читал на прошлой неделе в этой ветке?
Очень Важные для меня вещи обсуждались
Просьба не оставлять мое сообщение без ответа!!!http://arenda-n.ru/index.php?option=com_xmap&sitemap=1&Itemid=9 – Аренда квартир

vijay Says:

October 5th, 2009 at 12:11 am

same question i hav that of icodeblog…..
Is there a way to animate the squares? For example pass through an array of 6 .pngs to create animations? Maybe change all the blue squares to little spiders with moving legs?

Hammastyadack Says:

November 9th, 2009 at 8:15 am

Your welcome everyone.
My PC worked not correctly, too much errors. Help me, please to fix errors on my PC.
I used Windows XP.
With best regards,
Hammastyadack

Landolite Says:

December 9th, 2009 at 1:36 pm

Debased brand-new VIAGRA
You commitment not be dissapointed
Fixed at self-direction pills in the need of the like new world
Away joined readily!

adjoumjoino Says:

December 17th, 2009 at 2:06 pm

Hello,
My computer worked slowly, too much errors. Help me, please to fix errors on my PC.
My operation system is Windows XP.
Thx,
adjoumjoino

Will Culpepper Says:

January 15th, 2010 at 4:28 pm

The 5 lines that set up workingFrame can be replaced by a single line:

CGRect workingFrame = CGRectMake(15, 400, 40, 40);

Although for beginners it might be helpful to show what exact component of the working frame is being set.

JerryIB Says:

February 2nd, 2010 at 9:49 am

Нужен какой-нибудь дупликатор или ризограф. Можно б.у.Что лучше выбрать посоветуйте! Печатаем немного, пока. Возможно возьмём заказ на печать мини-газеты. Заранее СПАСИБО! Да забыл сказать формат наверное А3.

Leave a Reply