Bugs don’t always mean broken functionality

25 Nov
November 25, 2012

I was having an issue with one of our iOS apps that caused some major slowdowns. The app was loading cached data from the disk, but it was taking just as long as when it fetched from the web! Here’s a video demonstrating what happened:

Check after the break to see what was going wrong!

So this part of the code checks to see if a given chapter exists on disk, as well as checks a confirmation flag that was written as well. This makes sure that we don’t have any incomplete downloads assumed to be complete.

// Check if the file exists, and if it's check flag is present
if ([[NSFileManager defaultManager] fileExistsAtPath:soundPath] && trackConfirmation) {
    status = kTrackStatusDownloaded;
}
else { // One or both tests failed, make sure we nuke the file and the flag just in case it was just one
    [[DownloadManager sharedManager] removeTrack:self];
    [self clearTrackDownloadConf];
    status = kTrackStatusNotDownloaded;
}

This all seems perfectly logical. We set the status to downloaded if the file is there and the check passes, and clear both if the check fails.

The problem though, is that the file operation takes about .1 seconds to perform whether the file is there or not. When this becomes the default case for every chapter in your library, we have a problem.

The good thing is that the solution is really simple, just fill out all of the cases of the if statement:

// Check if the file exists, and if it's check flag is present
if (!exists && !trackConfirmation) {
    // Haven't done anything. SAVE CYCLES!
}
    else if (exists && trackConfirmation) { // Everything is there, golden
    status = kTrackStatusDownloaded;
}
    else if(exists){ // The file is there, but no complete flag. Kill the partial
    [[DownloadManager sharedManager] removeTrack:self];
    status = kTrackStatusNotDownloaded;
}
else if(soundPath) { // just the flag is there, get rid of it
    [self clearTrackDownloadConf];
}
else {
    // UHHHHH WHAT DID YOU DO?!?!
}

As you saw above, the performance improvement was substantial. So remember: just because it works, doesn’t mean it’s the best way.

Alex Glenn

Alex is a Product Developer at Findaway World who is obsessed with anything with a processor in it

More Posts - Website - Twitter - Facebook - LinkedIn - Google Plus

© Copyright 2017 Findaway. All rights reserved.