Adding an Assertion Macro in Objective-C
Join the DZone community and get the full member experience.
Join For FreeTL;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
Published at DZone with permission of Kristina Chodorow, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
AI Technology Is Drastically Disrupting the Background Screening Industry
-
WireMock: The Ridiculously Easy Way (For Spring Microservices)
-
Using DuckDB With CockroachDB
-
How To Become a 10x Dev: An Essential Guide
Comments