Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define constant based on device type

I have a Constants.h file which contains some global constants in fact. Since my application is built both for iPhone and iPad, i would like to define the same constants (ie with the same name) differently for the two device types.

For a complete explanation:

/******** pseudo code *********/

if (deviceIsIPad){
    #define kPageMargin 20
}
else {
    #define kPageMargin 10
}

How can I do this? Thanks.

L.

like image 260
Lolloz89 Avatar asked Aug 08 '12 09:08

Lolloz89


People also ask

How do we define constant?

constant implies uniform or persistent occurrence or recurrence.

What is constant in Android?

Magic constants are a response to the ever-growing number of APIs in the Android framework, where the state, type of a component, or an action are chosen by providing an int or String constant. For example, setting view visibility with int constants or requiring a system service with String constants.

Why use constant in programming?

Using a constant instead of specifying the same value multiple times can simplify code maintenance (as in don't repeat yourself) and can be self documenting by supplying a meaningful name for a value, for instance, PI instead of 3.1415926.


2 Answers

It's impossible to get device type during preprocessing step. It is determined dynamically during runtime. You have two options:

  1. Create two different targets (for iPhone and iPad respectively) and define macro there.

  2. Create macro that inserts expression like this:

 #define IS_IPAD    (UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad)

 #define kMyConstant1 (IS_IPAD ? 100 : 200)
 #define kMyConstant2 (IS_IPAD ? 210 : 230)
 #define kMyConstant3 (IS_IPAD ? @"ADASD" : @"XCBX")
like image 88
Max Avatar answered Sep 19 '22 13:09

Max


#define are resolved at compile time, ie on your computer

Obviously, you can't make them conditional the way you want. I recommend creating static variable and setting them on the +(void)initialise method of your class.

And for the condition, use something like

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {   
    // iPad 
} else {   
    // iPhone or iPod touch. 
}

So that would go

static NSInteger foo;

@implementation bar

+(void)initialise{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {   
        // iPad 
        foo = 42;
    } else {   
        // iPhone or iPod touch. 
        foo = 1337;
    }
}

@end
like image 34
Olotiar Avatar answered Sep 20 '22 13:09

Olotiar