Why oh why? or What was I thinking?

I was profiling some code today and saw a blip when a startup window closes. For some reason that I have yet to explain, I struggled with the code. What I ended up putting in was something like this:

[self performSelectorInBackground:@selector(closeStartupWindowInBackground)
                       withObject:nil];

with closeStartupWindowInBackground defined as:

- (void) closeStartupWindowInBackground
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[NSThread sleepForTimeInterval:1.5];
	[self performSelector:@selector(closeStartupWindow)];
	[pool drain];
}

Now, anyone that has done Objective-C for awhile knows that this is utter crap. Why spawn a new thread to simply do something after a delay? The correct way to do this is:

[NSTimer scheduledTimerWithTimeInterval:1.5
                                 target:self
                               selector:@selector(closeStartupWindow)
                               userInfo:nil
                                repeats:NO];

or

[self performSelector:@selector(closeStartupWindow)
           withObject:nil
           afterDelay:1.5]

In addition to spawning the thread, the original code closed the window on a background thread. Many parts of AppKit are not thread safe, so doing that could potentially crash.

Does anyone know why I’d do something so stupid as write that original code?

[Update: this gets worse, going back 9 months to my original code before I touched it, I had the performSelector code in there to begin with, but for some reason though that it would block the main thread. Granted it does block the main thread briefly while executing the close method, but that’s fine.]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.