Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#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!

like image 222
Daniel Arantes Loverde Avatar asked May 28 '12 22:05

Daniel Arantes Loverde


2 Answers

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

like image 72
allaire Avatar answered Oct 31 '22 11:10

allaire


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
  }
}
like image 30
Dave DeLong Avatar answered Oct 31 '22 09:10

Dave DeLong