Daniel Arantes Loverde
Daniel Arantes Loverde

Reputation: 2314

#define or #if statement error

I have read many definitions of # if and # define statement.
I tried to use the way I read, but only with the error "Invalid token at start of a preprocessor expression" on the line that defines it as a comment below:

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

#define is_ipad         (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define is_ipad_hd      ( (is_ipad == 1 && [UIScreen mainScreen].bounds.size.width > 1024 ) ? YES : NO)
#define is_iphone_hd    ([UIScreen mainScreen].bounds.size.width > 480 ? YES : NO)
#define device_width    480.0f
#define device_height   320.0f

#if (is_ipad_hd == YES) // Error here
  #define device_width       = 2048.0f
  #define device_height      = 1496.0f
#endif

Why it works in simple tutorials and when we try something more complex these things happen!

Upvotes: 6

Views: 5487

Answers (3)

shaunhusain
shaunhusain

Reputation: 19748

Agree with others here although I'm not as well versed in the C preprocessor a quick googling came back with this:

expression is a C expression of integer type, subject to stringent restrictions. It may contain.... much better formatting than I can quickly achieve here on the source.

Upvotes: 0

Dave DeLong
Dave DeLong

Reputation: 243156

Macro evaluation happens at compile time.

However, (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) or [UIScreen mainScreen] can only be interpreted at run time.

Beyond that, you should not be relying on the screen size to do your dirty work for you. You should instead be relying on the user interface idiom and the scale of the main screen:

BOOL isiPad = UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad;
BOOL isHD = [[UIScreen mainScreen] scale] == 2.0;

if (isiPad) {
  if (isHD) {
    // retina iPad
  } else {
    // non-retina iPad
  }
} else {
  if (isHD) {
    // retina iPhone/iPod touch
  } else {
    // non-retina iPhone/iPod touch
  }
}

Upvotes: 1

allaire
allaire

Reputation: 6045

These are preprocessor directives, so you don't have access to [UIScreen mainScreen] methods and all other objects that are defined upon compilation!

Upvotes: 5

Related Questions