Ozgur Vatansever
Ozgur Vatansever

Reputation: 52143

Prevent Compilation of Code Using Macro in Objective-C

I am trying to find a way to prevent user from even compiling the code based on value of some user-defined build setting such as DEBUG=1. First thing that popped out in my mind is to write a macro something like this;

#if DEBUG=1
    #define NS_UNAVAILABLE_IN_PROD NSLog(x);
#else
    #define NS_UNAVAILABLE_IN_PROD
#endif

so I am able use it like this;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   NS_UNAVAILABLE_IN_PROD

   self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
   self.window.backgroundColor = [UIColor blackColor];
}

When I try to compile the code, I get the error:

Use of undeclared identifier 'x'

which is expected, but in some cases, depending on the place where I put this check, a local variable x may be initialized before that so it passes without any error. Thus, I need a more clever way to inform user that the code can't be compiled because he is in DEBUG mode.

Upvotes: 1

Views: 385

Answers (1)

CRD
CRD

Reputation: 53000

If I understand the question you are looking for #error, e.g.:

#if DEBUG
#error "Will not compile"
#endif

After Comments

What I'm suggesting is you do:

#if DEBUG
#error "This method only available in production"
#endif
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
   self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
   self.window.backgroundColor = [UIColor blackColor];
}

It might be nice if you could define that as a macro itself, but I don't think you can.

You can place that code multiple times into a file.

You can also use _Static_assert as in the other question you've linked to:

#define DEBUG_ONLY _Static_assert (!DEBUG, "Only available in debug");

DEBUG_ONLY - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

but note you need to put it at the start of the line not at the end.

Upvotes: 2

Related Questions