NSTimer: The Poor Man’s Threading – Code Snapshot

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


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


You can get the source here: NSTimerDemo


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:

      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];


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

  • http://web-geeks.com Techy

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

  • Bergamot

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

    Or take a screenshot of the simulator.

  • http://web-geeks.com Techy

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

  • kenny


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

    you must also #import

  • http://maniacdev.com/2009/07/iphone-objective-c-programming-nstimer/ iPhone Objective-C Programming NSTimer | iPhone Development Tutorials and Tips

    [...] 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

    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.

  • http://maniacdev.com Maniacdev

    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.

  • http://www.shingle.dy.fi Mikko K

    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 :)

  • http://www.picomangames.com Picoman


    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


  • http://www.picomangames.com Picoman

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

  • http://reelchaos.com max

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

  • http://icodeblog.com/2009/07/27/1188/ Programmatically Getting a Screencapture of any UIView | iCodeBlog

    [...] 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

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

  • rully lukita

    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];

  • http://www.picomangames.com Picoman

    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?

  • http://pokroff.ru/index.php?option=com_xmap&sitemap=1&Itemid=27 ephellulk

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

  • http://arenda-n.ru arenda-n

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

  • vijay

    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

    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,

  • Landolite

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

  • adjoumjoino

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

  • http://www.eliolhan.com Will Culpepper

    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

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

  • kidumatarim

    קידום אתרים
    אם אתה רואה את המודעה הזאת -גם אחרים יראו אותה

    קידום אתרים ב שיטה החרת
    הפצה ושיווק בפורומים הינם כלי פרסום אפקטיביים וחדשניים.
    כלים אלה בעלי יתרונות בולטים:
    1. כאשר תוכן המודעה מנוסח היטב, מעל חצי ממבקרי הפורומים ייחשפו לתכניה ואחוז גבוה מהם יתעניינו ברכישת מוצרכם.
    2. קישור לאתרכם יופיע בעמודי פורומים רבים, הגורם לעלייה נכרת בפופולריות שלו (PAGE RANK) ועלייה למיקום גבוה בכל מנועי החיפוש, אשר ימשכו לקוחות רבים להתעניין במוצרכם.

    הפצה קבוה ומאסיבית בפורומים מאפשרת לקדם את אתרכם במהירות וביעילות ומבטיחה את מיקומו בעמוד הראשון בכל מנועי החיפוש.

    טלפון להזמנות 0548307374
    icq 303927119

  • http://www.MIXEDMARTIALARTSUFC.TK Sandi Stahmer

    I need some advice for my blog….I like your layout. Can you help me? 9 1 4

  • Joel Three

    Very Nice, thanks a bunch!