Think of the run loop! (aka ‘One Wasted Day’*)
May 8th, 2008 by rb
In order to gather more data for my diploma thesis (more on that later) I tried to write a small console application that queries Spotlight. In theory this was easy: The functionality was already provided in Cocoa and a proof of concept using F-Script worked flawlessly, so there shouldn’t be much of a problem hacking it in Python or Objective-C, right?
Maybe in a Side-Effects-FreeTM world, but in here I spent some hours reading and debugging until some nice IRC user politely (no joke intended) told me to think of the run loop.
So, to make a short story short, here are the fragments that finally did the trick for me:
int main(int argc, char *argv[]) { NSRunLoop *currentLoop = [NSRunLoop currentRunLoop]; // Query Spotlight in here // Let it run for a while ... while (mustContinue && [currentLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:1]]) { // Collect Results } }
In contrast, what does NOT work is:
// Query Spotlight sleep() // Collect Results
What put me on the wrong track was that startQuery() returns instantly, so I though “Okay, they must be spawning some new thread in the background and handle the rest, so it doesn’t matter what I do with this thread …”
(*)
Two hours: getting the idea and trying to make it work
Two hours: being curious why it doesn’t work.
Two hours: being depressed that it doesn’t work
Two hours: being outrageously furious that it still doesn’t work
Ten minutes: apathetically accepting that it doesn’t work and probably never will, asking on IRC for help.
After eight hours and twenty minutes: it works.