Adding an Assertion Macro in Objective-C


#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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: