Fahim Parkar
Fahim Parkar

Reputation: 31647

Comparing #define giving incorrect result

I have defined one variable which gives me output as below.

iPhone 4 >> 4
iPhone 5 >> 5
iPad >> 999

Function used is as below.

#define iPhone4Or5 [[UIScreen mainScreen] bounds].size.height == 568 ? 5 :
        ([[UIScreen mainScreen] bounds].size.height == 480 ? 4 : 999)

When I NSLog variable iPhone4Or5, it gives me correct result for iPhone 5, however when I make compare it gives me wrong result...

if (iPhone4Or5==999) {
    NSLog("Its iPad version");
} else {
    NSLog("Its iPhone version");
}

When I run above with iPhone 5 or above, it always gives me NSLog as Its iPad version.

Any idea why I am getting WRONG compare result?

I am defining variable in prefix.pch

Note:

If I execute NSLog("iPhone4Or5==%d", iPhone4Or5), I get output as iPhone4Or5==5

Upvotes: 0

Views: 87

Answers (2)

Ramaraj T
Ramaraj T

Reputation: 5230

Log the value of [UIScreen mainScreen] bounds].size.height and check if it 480.

Or you can use these.

#define IS_IPAD ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] && [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) 

#define IS_IPHONE5 ((( !IS_IPAD && [[UIScreen mainScreen] bounds].size.height == 568))?YES:NO)

Upvotes: 0

Paul R
Paul R

Reputation: 213059

You are having problems with operator precedence - your macro needs parentheses:

#define iPhone4Or5 ([[UIScreen mainScreen] bounds].size.height == 568 ? 5 : \
        ([[UIScreen mainScreen] bounds].size.height == 480 ? 4 : 999))

Better still, avoid this and other common macro-related problems and use a function instead:

int iPhone4Or5(void)
{
    const int height = [[UIScreen mainScreen] bounds].size.height;
    if (height == 568) return 5;
    if (height == 480) return 4;
    return 999;
}

Upvotes: 0

Related Questions