How to assure your values are as intended with NSAssert

NSAssert is a macro which allows you to test for specific values if and when they occur. Rather than having to figure out where your app has passed the wrong value several stages before a problem happened, NSAssert can be used like NSLog – with the helpful difference that if all is well, there’s no log output.

Imagine your app is calculating a value. We can check if the value is as we had expected it to be:

In this case, everything is fine and we don’t see any log output. Let’s change the value to something else, and see our message together with a rather intimidating stack trace hit our log:

You can also pass values and print them to the log. Depending on how many variables you pass, add a number to NSAssert like so:

Use NSAssert2, NSAssert3 and so forth for more than one value.

About Jay Versluis

Jay is a medical miracle known as Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

1 thought on “How to assure your values are as intended with NSAssert

  1. When it comes to releasing your application you’d assume that all NSAssets will validate without a problem. However, they’re technically still in your code and will compile with your Release Scheme. Even though that shouldn’t be a problem, some of us sleep better at night if those were not compiled when you submit your app to the App Store.

    Help is at hand with a small tweak to your Build Configuration:

    • head of over to your Build Settings
    • find the Preprocessing section, Preprocessor Macros
    • add a new line under Release called NS_BLOCK_ASSERTIONS

    This will exclude all NSAssert statements from your release build.

    Screen Shot 2014-05-05 at 09.41.06

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.