Sunday, October 16, 2011

How to wait while an NSTimer runs in a unit test

Suppose you were a lowly noob to iOS development. Further suppose you had a Cool Idea (tm) which involved timers. The internets might rapidly guide you to NSTimer and you might decide to try to get it to log to the console in a unit test. The most obvious approach seems to be to setup a timer to tick frequently, lets say every 0.1 seconds, and setup a timer callback that logs something, then make a test that sleeps for a couple of seconds. Presumably during the sleep period we'll see a bunch of timer output. The code might look like this (inside an XCode 4.2 test implementation class):

- (void)onTimerTick:(NSTimer*)timer
{
    NSLog(@"MY TIMER TICKED");
}

- (void)testTimerBasics
{
    NSLog(@"timer time");
    
    [NSTimer scheduledTimerWithTimeInterval:0.1
                   target:self
                   selector:@selector(onTimerTick:)
                   userInfo:nil
                   repeats:YES];
    
    [timer fire]; //manually calling fire DOES log 'MY TIMER TICKED'
    
    NSLog(@"about to wait");    
    [NSThread sleepForTimeInterval:2.0]; //absolutely no logs of 'MY TIMER TICKED' occur; somehow the time doesn't fire during a thread sleep :(
    NSLog(@"wait time is over");    
}

Sadly absolutely no log messages are printed during our two second sleep ([NSThread sleepForTimeInterval:2.0]) ; WTF?!

After much Google and literally in the midst of typing a Stack Overflow question I came across a question involving waiting for something else that mentioned NSRunLoop in passing. The very existence of a run loop class suggests an answer: our tests run on the same thread as the run loop. This means if we put the run loop to sleep nothing gets processed. Instead of sleep we need some sort of "run the run loop for a while" approach. Luckily it turns out that NSRunLoop provides a runUntilDate API so we can re-write the test above as follows:

- (void)onTimerTick:(NSTimer*)timer
{
    NSLog(@"MY TIMER TICKED");
}

- (void)testTimerBasics
{
    NSLog(@"timer time");
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1
                              target:self
                              selector:@selector(onTimerTick:)
                              userInfo:nil
                              repeats:YES];
    
    //[timer fire];
    
    NSDate *runUntil = [NSDate dateWithTimeIntervalSinceNow: 3.0 ];
    
    NSLog(@"about to wait");    
    [[NSRunLoop currentRunLoop] runUntilDate:runUntil];
    NSLog(@"wait time is over");    
}
We've found the right magic incantation! Knuth would be proud.

Speaking of magic incantations, I am using the SyntaxHighlighter libraries hosted @ http://syntaxhighlighter.googlecode.com/svn/trunk/Scripts/. However, there is no Objectionable-C brush there so I took the one posted @ http://www.undermyhat.org/blog/wp-content/uploads/2009/09/shBrushObjectiveC.js and updated it the casing and namespace names to the newer highlighter standard. The updated brush looks like this:


dp.sh.Brushes.ObjC = function()
{
 var datatypes = 'char bool BOOL double float int long short id void';
 
 var keywords = 'IBAction IBOutlet SEL YES NO readwrite readonly nonatomic nil NULL ';
 keywords += 'super self copy ';
 keywords += 'break case catch class const copy __finally __exception __try ';
 keywords += 'const_cast continue private public protected __declspec ';
 keywords += 'default delete deprecated dllexport dllimport do dynamic_cast ';
 keywords += 'else enum explicit extern if for friend goto inline ';
 keywords += 'mutable naked namespace new noinline noreturn nothrow ';
 keywords += 'register reinterpret_cast return selectany ';
 keywords += 'sizeof static static_cast struct switch template this ';
 keywords += 'thread throw true false try typedef typeid typename union ';
 keywords += 'using uuid virtual volatile whcar_t while';
 // keywords += '@property @selector @interface @end @implementation @synthesize ';
 
  
 this.regexList = [
  { regex: dp.sh.RegexLib.SingleLineCComments,  css: 'comments' },  // one line comments
  { regex: dp.sh.RegexLib.MultiLineCComments,  css: 'comments' },  // multiline comments
  { regex: dp.sh.RegexLib.DoubleQuotedString,  css: 'string' },   // double quoted strings
  { regex: dp.sh.RegexLib.SingleQuotedString,  css: 'string' },   // single quoted strings
  { regex: new RegExp('^ *#.*', 'gm'),      css: 'preprocessor' },  // preprocessor
  { regex: new RegExp(this.GetKeywords(datatypes), 'gm'),  css: 'datatypes' },  // datatypes
  { regex: new RegExp(this.GetKeywords(keywords), 'gm'),  css: 'keyword' },   // keyword
  { regex: new RegExp('\\bNS\\w+\\b', 'g'),     css: 'keyword' },   // keyword
  { regex: new RegExp('@\\w+\\b', 'g'),      css: 'keyword' },   // keyword
  ];
 this.CssClass = 'dp-objc';
 this.Style = '.dp-objc .datatypes { color: #2E8B57; font-weight: bold; }'; 
}
dp.sh.Brushes.ObjC.prototype = new dp.sh.Highlighter();
dp.sh.Brushes.ObjC.Aliases  = ['objc'];

41 comments:

Priya Kannan said...

It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command .
IOS Training in Chennai

Unknown said...

Really Good blog post.provided a helpful information.I hope that you will post more updates like this
ios Online Training Hyderabad

akhilapriya404 said...

I really enjoy the blog.Much thanks again. Really Great ios Online Course Bangalore

SRI said...

Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.

rpa Training in Chennai

rpa Training in bangalore

rpa Training in pune

blueprism Training in Chennai

blueprism Training in bangalore

blueprism Training in pune

rpa online training

shalinipriya said...

This is very good content you share on this blog. it's very informative and provide me future related information.
Data Science training in marathahalli
Data Science training in btm
Data Science training in rajaji nagar
Data Science training in chennai
Data Science training in kalyan nagar
Data Science training in electronic city
Data Science training in USA


simbu said...

This blog is the general information for the feature. You got a good work for these blog.We have a developing our creative content of this mind.Thank you for this blog. This for very interesting and useful.

java training in marathahalli | java training in btm layout

java training in jayanagar | java training in electronic city

java training in chennai | java training in USA

selenium training in chennai

Mounika said...

python training institute in chennai
python training in velachery
python training institute in chennai

Unknown said...

Great content thanks for sharing this informative blog which provided me technical information keep posting.
Blueprism training in Chennai

Blueprism online training

Blue Prism Training in Pune

pragyachitra said...

I think you have a long story to share and i am glad after long time finally you cam and shared your experience.

angularjs Training

in chennai

angularjs Training in chennai

angularjs-Training in tambaram

angularjs-Training in sholinganallur

angularjs-Training in velachery

cynthiawilliams said...

I have to thank for sharing this blog, it is really helpful.
RPA Training in Chennai
Robotics Process Automation Training in Chennai
RPA courses in Chennai
RPA Training
RPA course

Unknown said...

It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
python training in rajajinagar | Python training in btm | Python training in usa

LindaJasmine said...

Interesting Post. I liked your style of writing. It is very unique. Thanks for Posting.

Node JS Training in Chennai
Node JS Course in Chennai
Node JS Advanced Training
Node JS Training Institute in chennai
Node JS Training Institutes in chennai
Node JS Course

Sumaya Manzoor said...

All your points are excellent, keep doing great work
Selenium Training in Chennai
selenium testing training in chennai
iOS Training in Chennai
Digital Marketing Training in Chennai
android training center in chennai
best android training center in chennai

yuvaprithika said...

This is really too useful and have more ideas and keep sharing many techniques. Eagerly waiting for your new blog keep doing more.
Aws Training in Bangalore
Aws Course in Bangalore
Best Aws Training in Bangalore
hadoop classes in bangalore
Java Training in Bangalore
Best Java Training Institutes in Bangalore

Vicky Ram said...

Thank you for sharing this post.

toorizt
Article submission sites

Anbarasan14 said...

Thanks for sharing a worthy information. This is really helpful. Keep doing more.

English Speaking Course in JP Nagar Bangalore
Best Spoken English Coaching Center in JP Nagar
Spoken English Classes in Bangalore JP Nagar
French Training Institutes in JP Nagar
French Coaching Classes in JP Nagar
French Courses in JP Nagar
Best French Classes near me

LindaJasmine said...

Thanks for sharing such an amazing post. Your style of writing is very unique. It made me mesmerized in your words. Keep on writing.

Informatica Training in Chennai
Informatica Training Center Chennai
Best Informatica Training in Chennai
Informatica course in Chennai
Informatica Training center in Chennai
Informatica Training
Learn Informatica
Informatica course

Sai Elakiyaa said...

Great explanation, your article inspired me the most. Thanks for sharing.
Selenium Training in Chennai
Best Selenium Training Institute in Chennai
ios developer training in chennai
Digital Marketing Training in Chennai
.Net coaching centre in chennai
Future of testing professional
Different functions in testing
Digital marketing Training institute in chennai

mercyroy said...

I really thank you for your innovative post.I have never read a creative ideas like your posts.here after i will follow your posts which is very much help for my career.
Java Certification course in Bangalore
Java Courses in Nolambur
Java Training in Ashok Nagar
Java Training in Kelambakkam

cynthiawilliams said...

I have to thank for sharing this blog, really helpful. Keep sharing more like this.
ReactJS Training in Chennai
AngularJS Training Institute in Chennai
AngularJS Training in Chennai
AWS Training in Chennai
DevOps Certification in Chennai
Robotics Process Automation Training in Chennai
R Programming Training in Chennai
Data Science Course in Chennai

VenuBharath2010@gmail.com said...

You are an excellent writer. Amazing use of words. Waiting for your future updates.
Blockchain certification
Blockchain course
Blockchain Training
Blockchain Training Chennai
Blockchain Training in T Nagar
Blockchain Training in OMR

suresh said...

Excellent Article. Thanks Admin
Hadoop Big Data Training

Python Training in Chennai

kamal said...

indeed, I’m just always astounded concerning the remarkable things served by you. Some four facts on this page are undeniably the most effective I’ve had.
SOFTWARE TRAINING IN CHENNAI
POWERBI TRAINING IN CHENNAI
CCNA TRAINING IN CHENNAI
ANDROID TRAINING IN CHENNAI

KIT said...

Nice blog, it's so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job. Thank you for this wonderful sharing with us. Keep Sharing.
Kindly visit us @ 100% Job Placement | Best Colleges for Computer Engineering
Biomedical Engineering Colleges in Coimbatore | Best Biotechnology Colleges in Tamilnadu
Biotechnology Colleges in Coimbatore | Biotechnology Courses in Coimbatore
Best MCA Colleges in Tamilnadu | Best MBA Colleges in Coimbatore
Engineering Courses in Tamilnadu | Engg Colleges in Coimbatore

Unknown said...

Permainan poker membutuhkan skill dan pengalaman bermain serta sedikit teknik curang untuk bisa memenangkannya.
asikqq
http://dewaqqq.club/
http://sumoqq.today/
interqq
pionpoker
bandar ceme
freebet tanpa deposit
paito warna terlengkap
syair sgp

jefrin said...

It’s great to come across a blog every once in a while that isn’t the same out of date rehashed material. Fantastic read.
Data science Course Training in Chennai |Best Data Science Training Institute in Chennai
RPA Course Training in Chennai |Best RPA Training Institute in Chennai
AWS Course Training in Chennai |Best AWS Training Institute in Chennai
Devops Course Training in Chennai |Best Devops Training Institute in Chennai

Norton.com/setup said...

QuickBooks Desktop Tech Support Phone Number - With the latest software release of QuickBooks Desktop 2019, it has successfully outgrown other business software products in the competitive market. QuickBooks Desktop gives you the flexibility to manage your accounting, inventory, point of sale, payroll, payment and increase your productivity. It also allows you to track items, vendors and customers.

QuickBooks POS Tech Support Phone Number | QuickBooks Payroll Tech Support Phone Number

Softgen Infotech said...

Thank you for sharing such a nice post!

Softgen Infotech is the Best HADOOP Training located in BTM Layout, Bangalore providing quality training with Realtime Trainers and 100% Job Assistance.

raju said...

very nice blogger....!
inplant training in chennai
inplant training in chennai for it.php
panama web hosting
syria hosting
services hosting
afghanistan shared web hosting
andorra web hosting
belarus web hosting
brunei darussalam hosting
inplant training in chennai

dras said...

very nice post...
inplant training in chennai
inplant training in chennai
inplant training in chennai for it
Australia hosting
mexico web hosting
moldova web hosting
albania web hosting
andorra hosting
australia web hosting
denmark web hosting

shree said...

very nice....
inplant training in chennai
inplant training in chennai
inplant training in chennai for it
namibia web hosting
norway web hosting
rwanda web hosting
spain hosting
turkey web hosting
venezuela hosting
vietnam shared web hosting

subha said...

I am definitely enjoying your website. You definitely have some great insight and great stories. keep it up guys.
Ai & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai

tjproductstech said...


Hi, Very nice article. I hope you will publish again such type of post. Thank you!
Corporate gifts ideas | Corporate gifts
Corporate gifts singapore | Corporate gifts in singapore
Promotional gifts singapore | Corporate gifts wholesale Singapore
leather corporate gifts singapore | t shirts supplier singapore
thumb drive supplier singapore | business card holder singapore
corporate gifts supplier | customized corporate gifts singapore
corporate gifts supplier singapore

Altaj Shoes said...

Interesting stuff to read. Keep it up.Adidas showroom in madurai
Woodland showroom in madurai | Skechers showroom in Madurai
Puma showroom in madurai

Ramesh Sampangi said...

Data Science Course in Hyderabad by AI Patasala will be an ideal opportunity to get to know every Concept of Data Science with live demonstrations, real-time scenarios, and examples taught by experts.
Data Science Course in Hyderabad
Data Science Training in Hyderabad

French language classes in Chennai said...

wow really good informision got lot to learn. looking forward for more informative posts from you.
French Online Course | French Language Course | Online French Courses

ranjith said...

Thank you for this beautiful information, Also check
Coaching Centre In Bangalore
UI UX Course Bangalore
UI UX Design Course in Marathahalli
Best Training Institute In Marathahalli

iteducationcentre said...

Great Blog.Thanks for sharing such a wonderful blog.
AWS classes in Pune

Edit Institute said...

It's interesting how many of the bloggers helped me clarify a few things while also giving.The majority of ideas can be good material.Give them a good shake to get your point through and the demand across.
https://edit.co.in/ui-ux-design-course-in-bangalore.html

SHIVAM SHARMA said...

amazing writeup, keep posting and checkout our blog aws training in pune

SHIVAM SHARMA said...

informative blog keep posting aws training in pune

Post a Comment