Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 203
divergio Avatar asked Feb 16 '26 12:02

divergio


1 Answers

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.

like image 141
divergio Avatar answered Feb 18 '26 03:02

divergio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!