2

Simple question.

If I have

BOOL a = [myInst function];
NSAssert(a, @"...")

then I will get warnings in the release build because a is not used. I want to assert a BOOL returned from a function, but I don't need to use it. How would I fix it?

I can't put the whole expression into NSAssert because it won't compile in release.

ABCD
  • 7,914
  • 9
  • 54
  • 90
  • Sorry you'll have to rephrase your question as it doesn't make sense. – trojanfoe Aug 02 '12 at 08:31
  • With `#pragma unused(x,y,z)` you can tell the compiler that `x`, `y` and `z` aren't used; though I've only used that for function arguments and only with GCC, it might work for variables. This would have to appear inside an `#ifdef` that determines when `NSAssert()` is disabled (`#ifndef DEBUG` perhaps?). – Kevin Grant Aug 02 '12 at 08:34

5 Answers5

3

have you tried

#pragma GCC diagnostic ignored "-Wunused-variable"

<your function>

#pragma GCC diagnostic warning "-Wunused-variable"
AndersK
  • 35,813
  • 6
  • 60
  • 86
2

As long as the expression which results in a does not have side-effects, why not put it directly into NSAssert? E.g.

NSAssert(<expr>, @"...")

Note that if <expr> has side-effects, e.g. prints something, this may not happen in non-Debug builds.

jarmond
  • 1,372
  • 1
  • 11
  • 19
2

I dislike that warning.

Here is what I do in these cases:

BOOL a = NO;
a = [myInst function];
NSAssert(a, @"...")
Avi Cohen
  • 3,102
  • 2
  • 25
  • 26
1

Just mention the BOOL one more time:

a = !(!a); 

or

if (a) {}
Mundi
  • 79,884
  • 17
  • 117
  • 140
0

As mentioned in How to know if NSAssert is disabled in release builds?, you can use NS_BLOCK_ASSERTIONS to know if NSAssert is being overridden to do nothing.

Therefore, you can define your own assertion macro:

#ifdef NS_BLOCK_ASSERTIONS
    #define ABCAssert(condition, ...) \
        do { \
            if (!condition) \
                NSLog(__VA_ARGS__); \
        } while (0)
#else
    #define ABCAssert(condition, ...) NSAssert(condition, __VA_ARGS__)
#endif

Now replace all calls to NSAssert, with ABCAssert. In addition to ensuring that condition is always used, it will log any assertion failures rather than silently ignoring them.

Warning: I haven't tested the code above. When I have more time I will update it to ensure it works properly.


This is similar to Abizer Nasir's coding conventions which defines:

#ifdef DEBUG
  #define ALog(...) [[NSAssertionHandler currentHandler] handleFailureInFunction:[NSString stringWithCString:__PRETTY_FUNCTION__ encoding:NSUTF8StringEncoding] file:[NSString stringWithCString:__FILE__ encoding:NSUTF8StringEncoding] lineNumber:__LINE__ description:__VA_ARGS__]
#else
  #ifndef NS_BLOCK_ASSERTIONS
    #define NS_BLOCK_ASSERTIONS
  #endif
  #define ALog(...) NSLog(@"%s %@", __PRETTY_FUNCTION__, [NSString stringWithFormat:__VA_ARGS__])
#endif

There are a few differences, though:

Community
  • 1
  • 1
Senseful
  • 86,719
  • 67
  • 308
  • 465