nsstringshorthandstringwithformat

iOS stringWithFormat shorthand WITH nil check


I am trying to make a shorthand for [NSString stringWithFormat]:

How can I turn this (working):

  #define fstring(s, ...) [NSString stringWithFormat:(s), ##__VA_ARGS__]

into this (with a check for nil value)

  #define fstring(s, ...) [NSString stringWithFormat:(s), ##__VA_ARGS__ (__VA_ARGS__ ?:@"")]

Something like:

NSString *fullName = [NSString stringWithFormat:@"%@", contact.firstName ?: @""]

I have tried different shorthand combinations without luck... anybody got a better idea?

EDIT - Solution found

#define fstring(s, ...) [NSString stringWithFormat:(s), ##__VA_ARGS__ ?:@""]

Solution

  • Solution is the following:

    #define fstring(s, ...) [NSString stringWithFormat:(s), ##__VA_ARGS__ ?:@""]
    

    and if you want with empty string if null:

    #define fstringOrEmpty(...) __VA_ARGS__ ? : @""