Objective-C Preprocessor Expression for Debug Log
I have some code like this:
#define FORCE_DEBUG_MODE [[[NSUserDefaults standardUserDefaults] valueForKey:@"forceDebugMode"] isEqualToString:@"1"] #if defined DEBUG_MODE || defined FORCE_DEBUG_MODE #define DLog( s, ... ) NSLog( @"<%p %@:(%d)> %@", self, [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] ) #else #define DLog( s, ... ) #endif
I read from some article outside to use the preprocess marcos to define the DEBUG_MODE, however I would like to override the mode if I set a NSUserDefaults value to something.
These code got no errors. But seems that no matter what the FORCE_DEBUG_MODE is, defined FORCE_DEBUG_MODE equal to true. What I want is something like FORCE_DEBUG_MODE == 1
Please tell me if I can do this, and How?
you defined FORCE_DEBUG_MODE right above your check to see if it is defined. To check if it is true then you must just do || FORCE_DEBUG_MODE however that will as well be always true as It is only seeing if there is some value under the macro - this is all done in the preprocessor meaning none of this code will be ran or reran at runtime - these defines will define what code is actually compiled, not what code is ran
#if defined just checks whether the value has been defined, not what value it is. You can just use #if to check if a value is defined to a value other than zero.
This will still not work in your case though. The preprocessor runs before the compiler, so you cannot use it to switch in code at runtime. You need to perform the check for the defaults value at runtime.