I’m more of an Android developer, but i’m beginning to see the light at the end of the tunnel on iOS development.
There is, however, one coding pattern I can’t seem to find an equivalent for.
The use of static fields as flags.
Android :
public final static int ERROR_EMPTY = 1;
public final static int ERROR_NO_CONNECTION = 2;
public final static int ERROR_WRONG_USER = 4;
...
if (error == MyClass.ERROR_EMPTY) {//do things}
What would be the proper way to achieve this on iOS ?
Thanks.
Using Objective-C and C
i often use prefixes:
for these value collections. then you get benefits such as typesafety and
switchvalue checking.for non-type constants:
and feel free to hide these in the
*.mwhen private.also note that C
enums may have gaps in their defined values (unlike Java’s).Update: there’s an even better way to declare an enum, as demonstrated in Abizern’s answer — if you’re sticking with the most recent toolchains. the big reason to use this extension is for binary compatibility and encoding (although i favor fixed-width types for these purposes).
There are a few other variations, for the cases when you want to use existing types:
Private Constant
MyClass.m
Public Constant
MyClass.h
MyClass.m
Using C++
You would likely favor introducing a new scope for these values — either in a class or a namespace, rather than simulating the scope using prefixes.
Common Mistakes
#definefor constants (unless definition is mandatory when preprocessing)staticvalues in headersconstwhen possible*.msource.