简体   繁体   中英

Unused variable warning for variable used in NSAssert

I have a piece of code with a few variables that are used in an NSAssert statement only. They check for certain preconditions on method parameters that debug builds enforce more stringently. Here is an example:

NSString *videoCodec = [outputSettings objectForKey:AVVideoCodecKey];
NSNumber *width = [outputSettings objectForKey:AVVideoWidthKey];
NSNumber *height = [outputSettings objectForKey:AVVideoHeightKey];

NSAssert(videoCodec && width && height, @"OutputSettings is missing required parameters.");

NSAssert gets compiled out during the build process, resulting in an "unused variable" warning from the compiler. Note that this warning only occurs when I do a release build.

I know this usage is valid and safe, but how can I let the compiler know so it doesn't generate erroneous messages?

I found the solution, and further confirmed it when I saw that the same solution is already in the development version of this library.

The compiler warning can be silenced on a variable-by-variable basis with an "unused" attribute. "cdefs.h", which is included on iOS and should be in OS-X, includes a convenience definition pointed out here : #define __unused __attribute__((__unused__))

The resulting code looks like this:

__unused NSString *videoCodec = [outputSettings objectForKey:AVVideoCodecKey];
__unused NSNumber *width = [outputSettings objectForKey:AVVideoWidthKey];
__unused NSNumber *height = [outputSettings objectForKey:AVVideoHeightKey];

NSAssert(videoCodec && width && height, @"OutputSettings is missing required parameters.");

Alternatively, if it is possible to re-write the NSAssert statement without the intermediate variable, and without losing clarity, that is also an acceptable solution.

NSAssert resolves to an empty macro when building for release , thus if the variables are used only for assert purposes, you get the warning.

You could embed the debug block into an #ifdef DEBUG (assuming your DEBUG configuration defines this macro), in order to get rid of the warnings.

Edit Actually, the macro is not empty when building in release, but it does not make use of the passed arguments:

#define NSAssert(condition, desc, ...) do {} while (0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM