Why do Cocoa-Touch class ivars have leading underscore character?

痞子三分冷 提交于 2019-12-20 02:54:47

问题


Is there some purpose for this convention?


回答1:


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.




回答2:


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

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