Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declare a constant string with a condition

i have a source file to put all my constants ( constant.h) like this :

#define MY_URL @"url"
#define SECOND_URL @"url2"
...

my problèm is to déclare a constant with a condition like this :

if (ipad)
   #define MY_CONSTANT @"ipad"
else
   #define MY_CONSTANT @"iphone"

How i can do this please and put it in the constant.h ?

like image 753
samir Avatar asked Dec 21 '22 17:12

samir


2 Answers

if you support both ipad and iphone, you won't know the device until runtime.

if you use a constants header, then you might approach the device specific definitions as follows:

constants.h

NSString * MON_CONSTANT();

constants.m

NSString * MON_CONSTANT() {
  switch (UI_USER_INTERFACE_IDIOM()) {
    case UIUserInterfaceIdiomPhone :
      return @"iphone";
    case UIUserInterfaceIdiomPad :
      return @"ipad";
    default :
      return @"omg";
  }
}

Notes:

  • i recommend putting your constants someplace other than a constants header. there is usually a location (e.g. class) which which more closely related to the constant.
  • not using #define for your constants, use the extern NSString* const approach instead.
like image 81
justin Avatar answered Jan 08 '23 10:01

justin


#define MY_CONSTANT ( ipad ? @"ipad" : @"iphone" )

or

#define MY_CONSTANT ( (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? @"ipad" : @"iphone" )

Edit: The above is appropriate for a Universal app, where the decision is made in real time. If you want a compile time decision, then I typically use a PreProcessor Macro in the Xcode target of IPAD or IPHONE, even UNIVERSAL (to build 3 ways):

#if defined(IPHONE)
#define MY_CONSTANT 4
#elif defined(IPAD)
#define MY_CONSTANT 6
#elif defined (UNIVERSALO)
#define MY_CONSTANT ( ipad ? 6 : 4 )
#endif

I find it both tedious to write and tedious to read:

(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

So I create global BOOL variables and set the value in appDelegate (in initialize), and put an "extern BOOL iPad;" statement in my pch file. In initialize:

ipad = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? YES : NO;

I know I know, globals are bad etc etc - and yes, if you over use them, but for something like this they are perfect.

like image 24
David H Avatar answered Jan 08 '23 09:01

David H