5

I need to make a define but if I use iPad or iPhone I need different values in this case.

So, as I think it should looks like this:

#ifdef UI_USER_INTERFACE_IDIOM == iPAD
#define ROWCOUNT 12
#else
#define ROWCOUNT 5
#endif

Is there some solution to get it?

Matrosov Alexander
  • 20,713
  • 42
  • 130
  • 259

3 Answers3

8

UI_USER_INTERFACE_IDIOM is a macro that expands to some expression that checks the type of hardware at runtime, not at compile time. Thus you would want to change your definition of ROWCOUNT to be a variable rather than a const or macro.

NSUInteger rowCount;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    rowCount = 12;
else
    rowCount = 5;

or more concisely:

NSUInteger rowCount = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? 12 : 5;
Mike Mertsock
  • 11,120
  • 7
  • 39
  • 72
7

#ifdef doesn't really do what you want here.

A good solution would be:

#define ROWCOUNT ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) ? 5 : 12)
Chris Knadler
  • 2,761
  • 2
  • 23
  • 32
  • 2
    Minor change recommended - make sure you enclose the entire expression in ()'s. Otherwise, a statement like if (ROWCOUNT == 5) will be interpreted incorrectly. – sbaker Aug 06 '13 at 21:12
  • yes, I have just seen warning and added () immediately. Xcode is very smarty ) – Matrosov Alexander Aug 06 '13 at 21:19
  • @ChrisKnadler few guys advice that I need to use instance variable instead of macros define. Are they right or no or maybe it depends? Which solutions is better? – Matrosov Alexander Aug 06 '13 at 21:21
  • 1
    @MatrosovAlexander My solution is in macro form. It's short but needs to be evaluated each time it is used as it is just replacing "ROWCOUNT" with the right hand side of the macro inline. I would probably use esker's solution in most cases, but if you want a macro, this is the way to do it. – Chris Knadler Aug 06 '13 at 21:23
5

This approach correctly identifies availability of UI_USER_INTERFACE_IDIOM:

#ifdef UI_USER_INTERFACE_IDIOM
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#else
#define IS_IPAD false
#endif

#define ROWCOUNT (IS_IPAD ? 12: 5)

You can also use the IS_IPAD macro as below:

NSUInteger rowCount;
if (IS_IPAD){
    rowCount = 12;
}else{
    rowCount = 5;
}
Brody Robertson
  • 8,107
  • 2
  • 40
  • 42