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



23 Comments
Very Cool! Do you think that you guys could make a tutorial on how to add screenshots to your app?
Techy: Hold the home button, and press the sleep button.
Or take a screenshot of the simulator.
I know that, I mean making it so it takes a screenshot by pressing a button within the app…
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
you must also #import
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.
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.
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?
Hi,
Great stuff!
Just one thing though.
The two lines of code below produce four errors and i am unsure what the < 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
Well is guess < gets translated to & l t on this site. Ignore previous post. :-S
im getting a warning NSTimer may not respond to + scheduledTimerWithTimeInterval…
Maybe a silly question (noob inside
), but myView are not released ? It should be ?
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….
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?
Центр Кровли — это современная компания, специализпрующаяся на реализации кровельных и отделочных материалов, Мы осуществляем монтаж кровли из металлочерепицфы. Являясь дистрибьютором многих производителей, мы можем гарантировать качество кровельных работ . Мы имеем сооответствующую лицензию на мнотаж кровли . Компания оказывавет полный комплекс услуг для реализации намеченных планов в одном месте: изготовление мягкой кровли – все это вы можете смело доверить нам.
Мы работаем уже более 10 лет на рынке кровельных материалов, и за это время компания доказала свою ответственность. Мы стремимся создать более удобные условия работы для клиентов, поэтому наши представительства находятяс в городах Пенза, Саратов Саранск и Москва. С 2009 года открыт филиал Центра Кровли в Московской области с собственным произвдсотвом металлочерепицы профиля «СуперМонтеррей» с полимерным покрытием, а также комплектующих элементов
Где все сообщения и темы которые я читал на прошлой неделе в этой ветке?
Очень Важные для меня вещи обсуждались
Просьба не оставлять мое сообщение без ответа!!!http://arenda-n.ru/index.php?option=com_xmap&sitemap=1&Itemid=9 – Аренда квартир
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?
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
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!
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
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.
Нужен какой-нибудь дупликатор или ризограф. Можно б.у.Что лучше выбрать посоветуйте! Печатаем немного, пока. Возможно возьмём заказ на печать мини-газеты. Заранее СПАСИБО! Да забыл сказать формат наверное А3.
קידום אתרים
אם אתה רואה את המודעה הזאת -גם אחרים יראו אותה
קידום אתרים ב שיטה החרת
הפצה ושיווק בפורומים הינם כלי פרסום אפקטיביים וחדשניים.
כלים אלה בעלי יתרונות בולטים:
1. כאשר תוכן המודעה מנוסח היטב, מעל חצי ממבקרי הפורומים ייחשפו לתכניה ואחוז גבוה מהם יתעניינו ברכישת מוצרכם.
2. קישור לאתרכם יופיע בעמודי פורומים רבים, הגורם לעלייה נכרת בפופולריות שלו (PAGE RANK) ועלייה למיקום גבוה בכל מנועי החיפוש, אשר ימשכו לקוחות רבים להתעניין במוצרכם.
הפצה קבוה ומאסיבית בפורומים מאפשרת לקדם את אתרכם במהירות וביעילות ומבטיחה את מיקומו בעמוד הראשון בכל מנועי החיפוש.
טלפון להזמנות 0548307374
icq 303927119
I need some advice for my blog….I like your layout. Can you help me? 9 1 4
2 Trackbacks
[...] 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 [...]
[...] 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 [...]