Celebrating 10 Years!

profile picture

#define

December 13, 2013 - Roundwall Software

When to use #define:

  1. When you’re declaring macros like in Apple’s:

    #define UI_USER_INTERFACE_IDIOM() ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] ? [[UIDevice currentDevice] userInterfaceIdiom] : UIUserInterfaceIdiomPhone) 
    

I’m actually not even sure why this wasn’t made as a function like NSLog instead of a macro.

When not to use #define:

  1. When you’re declaring constants. Constants should look like:

    NSString *const RWSSomeConstantName = @"theValueDoesn'tUsuallyMatter";
    const NSInteger RWSIntegerConstant = 3;
    

Why go through this effort to type extra letters?

  1. Constants declared using #define don’t show up in tools like the debugger. #define is raw text substitution, constants are symbols to your debugger, like class names.
  2. #define won’t warn you if you use #define in some other file and change the value of your constant accidentally.