This is part of an ELC Tech Network

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:

NSTimer *myTimer;
Advertisement

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.

This entry was posted in Code Snippets, Uncategorized and tagged , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

23 Comments

  1. Posted July 23, 2009 at 1:03 pm | Permalink

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

  2. Bergamot
    Posted July 23, 2009 at 1:24 pm | Permalink

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

    Or take a screenshot of the simulator.

  3. Posted July 23, 2009 at 2:07 pm | Permalink

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

  4. kenny
    Posted July 23, 2009 at 6:49 pm | Permalink

    UIGraphicsBeginImageContext(self.view.bounds.size);

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

    you must also #import

  5. Rein Hillmann
    Posted July 24, 2009 at 12:23 am | Permalink

    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.

  6. Posted July 24, 2009 at 12:30 am | Permalink

    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.

  7. Posted July 26, 2009 at 4:59 am | Permalink

    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?

  8. Posted July 26, 2009 at 5:25 am | Permalink

    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

  9. Posted July 26, 2009 at 5:27 am | Permalink

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

  10. Posted July 26, 2009 at 3:44 pm | Permalink

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

  11. Sylvain
    Posted August 18, 2009 at 8:54 am | Permalink

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

  12. rully lukita
    Posted August 18, 2009 at 12:57 pm | Permalink

    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….

  13. Posted August 31, 2009 at 7:01 am | Permalink

    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?

  14. Posted September 9, 2009 at 8:49 am | Permalink

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

  15. Posted September 28, 2009 at 4:14 am | Permalink

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

  16. vijay
    Posted October 5, 2009 at 12:11 am | Permalink

    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?

  17. Hammastyadack
    Posted November 9, 2009 at 8:15 am | Permalink

    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

  18. Landolite
    Posted December 9, 2009 at 1:36 pm | Permalink

    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!

  19. adjoumjoino
    Posted December 17, 2009 at 2:06 pm | Permalink

    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

  20. Posted January 15, 2010 at 4:28 pm | Permalink

    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.

  21. JerryIB
    Posted February 2, 2010 at 9:49 am | Permalink

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

  22. kidumatarim
    Posted April 1, 2010 at 2:50 am | Permalink

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

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

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

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

  23. Posted April 3, 2010 at 7:51 pm | Permalink

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

2 Trackbacks

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

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

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">