Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to name a constant in Objective-C?

What's the naming convention for constants in Objective-C (or most widely used way to name them)?

Is there a different criteria for extern constants?

Some styles I have seen:

NSString* const kPreferenceFirstRun = @"FirstRun";  // Replace "XY" by a prefix representing your company, project or module NSString* const XYPreferenceFirstRun = @"FirstRun";  
like image 288
hpique Avatar asked Oct 30 '10 10:10

hpique


People also ask

What is the convention for naming a constant?

Constants should be written in uppercase characters separated by underscores. Constant names may also contain digits if appropriate, but not as the first character.

Why do constants start with K?

No reserved words start with k so it is easier as a search target. Alternatively, from a graphical aspect, as a leading character it provides a very clear flag in front of the rest of the name.


2 Answers

After a bit of googling I've found the official coding guidelines for Cocoa.

To sum up:

  • Start with a two- or three-letter prefix in ALL-CAPS
  • Rest in UpperCamelCase
  • Same criteria for extern constants

I agree with itaiferber that the k prefix style is clearer and also much more useful for autocompletion. It would be interesting to know if this style is more popular than the official guidelines.

like image 66
hpique Avatar answered Sep 21 '22 02:09

hpique


it's seems to me, the best practice is to name constants in upper-case. but cocoa-core developers don't seem to share my opinion)) they use CamelCase for constants

like image 22
heximal Avatar answered Sep 23 '22 02:09

heximal