Like many things in iOS development (and all software development really), there’s the right way to do something, and then there are dozens of articles and forum posts describing various wrong ways to do it.
One I ran into recently was application-wide constants. The top voted answers on stack overflow seemed to be a bit odd looking to me. They usually advocated using some kind of #define
to create constants. Further digging revealed what appears to be the safer, more robust and better way to do constants.
To preface this, I’ll say that this is useful for application-wide constants only. If you have a single class with constants, this probably won’t help other than to demonstrate the syntax for constants. This method is definitely the easiest and fastest way to get your constants created and accessible everywhere in your app.
First, you’ll need to create a AppConstants.h file and its corresponding AppConstants.m file. Next, in the interface, you should add an extern <type> const <constant name>
. For example, I could say extern NSString* const APP_IDENTIFIER
. Now I have a string constant allocated for use. The “extern” allows us to declare this constant here in the interface. Next, we need to initialize or define our constant with the constant value. This is done in the corresponding AppConstants.m file. For this example, it would look like NSString* const APP_IDENTIFIER=
“HELLO_WORLD”@.
Now if you try to start using this constant in your classes, you’ll quickly find it doesn’t work. We need to let the application know about our AppConstants class. The best way to do this is to import it in the prefix header. This file is automatically generated for you and should be found in the supporting files folder. It will have a suffix of Prefix.pch. In that file, inside the #ifdef __OBJC__
, simply #import your AppConstants.h file.
You may need to clean the build before Xcode notices the new constant, but after that, you are able to use that constant anywhere in your application.
One of the advantages of this method over something like #define
and other methods is that you can actually compare your NSString constant to a string literal directly using == (good job compiler!). This will obviously be much faster than :isEqualToString
. Xcode will warn about this, and I would personally try to avoid it, but it does work.
As almost always, spending the time looking something up and understanding before using it helps to create a better and more robust product.