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:

    // NSAssert Example (nothing happens)
    int i = 47;
    NSAssert(i == 47, @"That didn't work");

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:

    // NSAssert Example (will cause an exception)
    int i = 48;
    NSAssert(i == 47, @"That didn't work");

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:

    // NSAssert Example (pass one value)
    int i = 48;
    NSAssert1(i == 47, @"The real value is %i", i);

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





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.