Created
June 8, 2013 06:42
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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