Is there some purpose for this convention?
Apple likes to use underscores to mean "private", according to the Coding Guidelines for Cocoa:
Avoid the use of the underscore character as a prefix meaning private, especially in methods. Apple reserves the use of this convention. Use by third parties could result in name-space collisions; they might unwittingly override an existing private method with one of their own, with disastrous consequences.
Method names beginning with underscores are reserved according to The Objective-C Programming Language (which means they're reserved even if you don't use Cocoa, presumably):
Method names beginning with “_”, a single underscore character, are reserved for use by Apple.
Additionally, the C/C++ convention is that leading underscores are (often) reserved for the implementation. A lot of people misinterpret this and use _ for anything "private"; leading to the proliferation of _FooLog() calls in a large chunk of our codebase, even though it invokes undefined behaviour.
The only reason to do it is to discourage direct ivar access in your own class. Prevent ivar access from other classes with @private
.
There are some developers who use the following convention of "hiding" there ivars by the following method:
@interface
@private
NSString *_myString
@property (nonatomic, retain) NSString *myString;
@implementation
@synthesize myString = _myString.
what this does is disallow direct access to the ivar with forcing all access via the property myString. Its a way of hiding the internals of your class and abiding by the object oriented principle of encapsulation.
来源:https://stackoverflow.com/questions/3544067/why-do-cocoa-touch-class-ivars-have-leading-underscore-character