Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Adding an Assertion Macro in Objective-C

DZone's Guide to

Adding an Assertion Macro in Objective-C

· Mobile Zone
Free Resource

Get gorgeous, multi-touch charts for your iOS application with just a few lines of code.

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

.Net developers: use Highcharts, the industry's leading interactive charting library, without writing a single line of JavaScript.

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 DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}