Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Best way to define Constants in Objective-C

I am defining constants with proper naming convention in objective-C but after having some search on internet, I found three different naming conventions for defining the constants. Those of given below.

NSString *const kModel_userID;
NSString *const k_model_user_id;
NSString *const kUserId;

Please check these and help me out which is the best way convention for constants in objective-C. Please give me valid reason if you like any convention. Also If you have any other convention please share that too. Thanks

like image 455
junaidsidhu Avatar asked Mar 23 '23 06:03


1 Answers

Prefix + Scope/Class + Identifier/Detail + Suffix/ConstantType.

Omit what does not apply.


// A NSNotification name, pertaining to NSApplication
PrClass      Identifier      SuffxType

Pretty idiomatic and easy to grok, IMO ;)

You use a similar form with enums:

// enum NSApplicationDelegateReply
PrClass      Enum         Identifier

I should also note that you should choose prefixes for your APIs which have 3 or more characters, to reduce the likelihood of colliding with Apple's or others' APIs.

The k prefix is an older convention. You will find it in many of the C APIs on OS X and iOS, such as the Core* frameworks. It's not very idiomatic for Objective-C APIs these days. It's used in some third party projects, but the uppercase prefix convention is most recognizable for Objective-C. Even the k prefixed constants use identifiers to 'namespace' their APIs, e.g. kCTLineTruncationStart. Smart.

like image 183
justin Avatar answered Mar 24 '23 20:03