Skip to content

Instantly share code, notes, and snippets.

@MaxGabriel
Created June 8, 2013 06:42
Show Gist options
  • Save MaxGabriel/5734318 to your computer and use it in GitHub Desktop.
Save MaxGabriel/5734318 to your computer and use it in GitHub Desktop.
Example showing how casting to BOOL causes failure 6% of the time, as explained in http://www.mikeash.com/pyblog/friday-qa-2012-12-14-objective-c-pitfalls.html
int failsUsingCurrentMethod = 0;
int failsUsingNotNot = 0;
for (int i=0; i < 10000; i++) {
NSDate *date = [NSDate date];
NSAssert(date, @"Date should never be nil");
BOOL booleanUsingCurrentMethod = (date);
if (!booleanUsingCurrentMethod) {
failsUsingCurrentMethod++;
}
BOOL booleanUsingNotNot = !!(date);
if (!booleanUsingNotNot) {
failsUsingNotNot++;
}
}
NSLog(@"Fails using current method = %i, which is %g percent of cases",failsUsingCurrentMethod,(failsUsingCurrentMethod/10000.0)*100);
NSLog(@"Fails using !! AKA convert to boolean = %i, which is %g percent of cases",failsUsingNotNot,(failsUsingNotNot/10000.0)*100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment