Shalin Shah
Shalin Shah

Reputation: 8183

How to put a #define in an if statement - Objective-C

I am making an iPhone app and I want to do widescreen detection so I made a bunch of #define's and I wanted to make an if statement with it.

// Device and Widescreen Detection
#define IS_WIDESCREEN ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )

// iPhone
#define IS_IPHONE ( [ [ [ UIDevice currentDevice ] model ] isEqualToString: @"iPhone" ] )  || ( [ [ [ UIDevice currentDevice ] model ] isEqualToString: @"iPhone Simulator" ] ) )
#define IS_IPHONE_5 ( IS_IPHONE && IS_WIDESCREEN )

// iPod Touch
#define IS_IPOD   ( [ [ [ UIDevice currentDevice ] model ] isEqualToString: @"iPod touch" ] )
#define IS_IPOD_5 ( IS_IPOD && IS_WIDESCREEN )

// iPad
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

I want to make an if statement saying that

if (IS_IPHONE_5) {
...
} else {
...
}

The problem is that the if statement returns an error and XCode keeps telling me to do this

if (IS_IPHONE_5 {
...
} else {
...
}

or this

if IS_IPHONE_5 {
...
} else {
...
}

otherwise it gives an error. Which is the correct way to write this?

Upvotes: 0

Views: 1527

Answers (1)

Jack
Jack

Reputation: 133609

You are missing a parenthesis in you IS_IPHONE macro definition. You have:

( [ [ [ UIDevice currentDevice ] model ] isEqualToString: @"iPhone" ] )  || ( [ [ [ UIDevice currentDevice ] model ] isEqualToString: @"iPhone Simulator" ] ) )

but you should have:

( ( [ [ [ UIDevice currentDevice ] model ] isEqualToString: @"iPhone" ] )  || ( [ [ [ UIDevice currentDevice ] model ] isEqualToString: @"iPhone Simulator" ] ) )

To find these kind of errors you can easily use the command from menu Product -> Generate Output -> Preprocessed File. In this way your preprocessor macros will be expanded and you will be able to see the final code, hence where is the error.

enter image description here

Upvotes: 14

Related Questions