cat
cat

Reputation: 367

How to define variable depend on condition in XCode

I want to define some variables depend on whether it is run on Iphone or Ipad application. So I wrote this code

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
    #define ABC @"122"
    NSLog(@"Ipad");
} else {
    #define ABC @"123"
    NSLog(@"iphone ");
}
NSLog(@" %@", ABC);

But in both iphone and Ipad it show 123.

Upvotes: 0

Views: 1294

Answers (2)

Igor Bidiniuc
Igor Bidiniuc

Reputation: 1560

Try this out:

#define ABC (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad ? @"122" : @"123")

This should work fine for you.

Upvotes: 3

sch
sch

Reputation: 27506

#define tells the preprocessor to modify every occurrence of ABC in the source code by the value associated with it.

ABC will be substituted with @"122" in all the lines that follow the line #define ABC @"122" and by @"123" in all the lines that follow the line #define ABC @"123".

This step happens at build time and not runtime. So you should define ABC as a string and set its value as follows:

NSString *ABC;
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
    ABC = @"122";
    NSLog(@"Ipad");
} else {
    ABC = @"123";
    NSLog(@"iphone ");
}
NSLog(@"%@", ABC);

Upvotes: 3

Related Questions