Over a million developers have joined DZone.

Adding an Assertion Macro in Objective-C

· Mobile Zone

TL;DR:

#define CHECK(val) NSAssert((val), @#val)
 
// Then use:
CHECK(/* something (hopefully) true */);

Long version:

iOS made the the somewhat bizarre choice that dereferencing a null pointer is not an error. The program just ignores that line and keeps going. Now this causes fewer crashes (yay-ish), but when I developing I’d really like the program to fail fast instead of just skipping huge swaths of code.

As far as I can tell, there’s no way to make dereferencing a null pointer an error. Thus, I’ve started adding asserts everywhere that I expect values to not be null:

NSAssert(my_var != nil, @"my_var isn't supposed to be nil");

I wrote that all of once and decided I needed a macro:

#define CHECK(val) NSAssert((val), @#val)

Now, I can just say:

CHECK(my_var != nil);

At compile time, the assert’s message will automatically be set to the string @"my_var != nil" (that’s what the preprocessor instruction # does: it means “wrap in quotes”).

Most libraries have a macro like this for asserting, but I’ve never programmed it myself. Nifty stuff!

P.S. If you need to debug the macro, you can run Objective-C files through GCC normally to see the preprocessor output:

$ gcc -E Gremlins.m > Gremlins.E
Topics:

Published at DZone with permission of Kristina Chodorow, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}