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?
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...