Vinod Vishwanath
Vinod Vishwanath

Reputation: 5891

How to use Ternary Operators in a Macro in Objective-C?

I have a Universal iOS app that loads certain pages into the UIWebView for the user to see. Now there are a different set of pages for iPad and iPhone(each device type has its own directory of pages).

To redirect to the right page based on device type, my code in Xcode mentions the device type in the query string. I'm trying to do this through a macro:

#define BaseURL @"http://someurl/Pages/Login.aspx?"
#define QueryStringParam (UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad) ? @"deviceType=iPad" : @"deviceType=iPhone"
#define LoginPageUrl    BaseURL QueryStringParam

The second macro here throws a compilation error "Called object type NSString* is not a function or function pointer"

So can I solve my problem at all using Macros? What's the right syntax to use ternary operators in a Macro?

Upvotes: 1

Views: 1719

Answers (1)

kennytm
kennytm

Reputation: 523214

The string concatenation with adjacent string literals only works when both are string literals, i.e.

@"foo" @"bar"       is the same as         @"foobar"

because @"foo" and @"bar" are string literals, but

@"foo" (@"bar")     is compiler error

because of the ( in between. This is the same situation as yours. In this case, you'd better concatenate the two strings in runtime:

#define LoginPageUrl    [BaseURL stringByAppendingString:(QueryStringParam)]

or force the compiler to see two adjacent string literals by combining the BaseURL and QueryStringParam

#define LoginPageUrl \
    ((UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad) ? \
        BaseURL @"deviceType=iPad" : \
        BaseURL @"deviceType=iPhone")

Upvotes: 4

Related Questions