Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do underscore prefixed variable names in Objective-C mean?

I noticed that in many community Objective-C classes and in Apple's frameworks they name some of the variables using a convention that prefixes variables with an underscore, such as: _name. What is the reason for having the underscore. Should I be doing this in my own classes? If so where and when should I use it?

like image 394
Justin Meiners Avatar asked Dec 05 '25 15:12

Justin Meiners


2 Answers

That's called uglification. The point is that you never use it, so no variable name or #define you create could ever interfere with Apple's code.

Ironically, many people create header guards with such names, because they see the system headers do it.

From C99 7.1.3 "Reserved identifiers":

All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.

(They mean reserved for the system library.)

Note: I'm not sure of the exact relationship between C99 and Apple ObjC, but you might as well have naming conventions that work across the entire C language family. In particular ObjC++ would require valid C++ names, which have the additional requirement of no double underscores anywhere.

like image 119
Potatoswatter Avatar answered Dec 07 '25 03:12

Potatoswatter


In Cocoa, it's a convention to indicate the something is private and shouldn't be used externally. However, it's unofficial convention, particularly in light of wording like this in the documentation:

Method names beginning with “_”, a single underscore character, are reserved for use by Apple.

However, that recommendation specifically applies to methods, not variables. So if you'd like to prefix your variables with underscores, go right ahead. That being said, if you're using the underscore prefix to indicate the private nature of some data, perhaps you shouldn't be exposing it in the first place...

like image 32
Dave DeLong Avatar answered Dec 07 '25 04:12

Dave DeLong