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

[亡魂溺海] 提交于 2020-01-23 13:58:47

问题


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?


回答1:


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




回答2:


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.




回答3:


Underscores get in the way of readability. Also with LLVM in place of GCC, I am getting rid of header side ivars and using header side properties. Be sure to make your properties non atomic unless you really want reads and writes synchronized for thread safety. unless you specify non atomic, it will default to atomic - which will deprive you of some performance.

also by convention, never start accessors with get. setters Should start with set but no getters with get. Read up on KVO and KVC for more about the conventions and what they are good for.

I do however like underscores in Enumeration naming list. Here the underscores help me pick out the suffix in 5 or more lines that all start with the same stem. Like typedef NSInteger COMPASS_DIRECTION; enum { COMPASS_DIRECTION_NORTH, COMPASS_DIRECTION_EAST, COMPASS_DIRECTION_SOUTH, COMPASS_DIRECTION_WEST, };



来源:https://stackoverflow.com/questions/3851739/what-do-underscore-prefixed-variable-names-in-objective-c-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!