Search code examples
iosmacroscompiler-warningsunused-variables

iOS: issues using variables inside MACRO


Can anyone please tell me why following Warns me "unused variable variable str"? SetAccessibilityLabelForView is a MACRO.

NSString *str = [NSString stringWithFormat:dynString, index];
SetAccessibilityLabelForView(myView, str);

dynamicString is setup in singleton class like "dynamic%d".

Macro:

#if RUN_TESTS
#define SetAccessibilityLabelForView(view, label) view.accessibilityLabel = label
#else
#define SetAccessibilityLabelForView(view, label)
#endif

WARNING comes for both the cases when RUN_TESTS true or false but if I removed else part then Warning goes away!

I have tried using following to get rid of warning,

  SetAccessibilityLabelForView(myView, [NSString stringWithFormat:dynString, index])

that gives me ERROR: "Too many arguments provided to function-like macro invocation"!

Then I have changed my macro to following,

#if RUN_TESTS
#define SetAccessibilityLabelForView(view, label, ...) view.accessibilityLabel = label
#else
#define SetAccessibilityLabelForView(view, label, ...)
#endif

Now same line works when RUN_TESTS FALSE but gives error "Expected ']'" when RUN_TESTS is TRUE!! Phew!!

Can someone please help me here. I want to get macro working for both the cases but just want to ignore lines generated by macro when RUN_TESTS is FALSE.


Solution

  • I couldn't resolve this issue! I am ended up ignoring unsused variable warning like below.

    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Wunused-variable"
    
    NSString *str = [NSString stringWithFormat:dynString, index];
    SetAccessibilityLabelForView(myView, str);
    
    #pragma clang diagnostic pop
    

    [EDIT]

    Finally I came out with better solution writting another macro to support formatted string..

    #if RUN_TESTS
    #define SetAccessibilityFormatedLabelForView(view, labelFormat, ...) view.accessibilityLabel = [NSString stringWithFormat:labelFormat, __VA_ARGS__]
    #else
    #define SetAccessibilityFormatedLabelForView(view, labelFormat, ...)
    #endif
    

    Usage:

    SetAccessibilityFormatedLabelForView(myView, dynString, index);