开发者

Preferred way to name instance variable in Objective C [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

When do you make an underscore in front of an instance variable?

As in Objective C, instance variable are protected by default, what are your preferred way to name it?

Assume you have an variable name, the following 3 ways have their supporters.

  1. _foo开发者_运维百科
  2. foo_
  3. foo


foo. I have always disdained the _foo or foo_ styles.


Apple's Coding Guidelines for Cocoa suggest you avoid an underscore prefix:

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.

and since I'm not aware of any trailing underscore convention, I don't know why you shouldn't use just foo.


You are not supposed to use underscore as a prefix as per _foo - that is reserved for Apple (and keeps you from accidentally re-defining a variable you do not know about!)

I like foo_, but only if you are writing accessors. Otherwise I just use foo. However for memory uses alone, it's good practice to always use accessors and just declare the ones you do not want public in a private category in the implementation like so:

@interface MyClass ()
@property (nonatomic, retain) NSArray *myArray;
@end

@implementation
@synthesize myArray = myArray_;
@synthesize myPublicString = myPublicString_;

- (void) dealloc
{
   [myArray_ release]; myArray_ = nil;
   [myPublicString_ release]; myPublicString_ = nil;
}

....

@end


Since I seem to be in the minority, I'll go ahead and throw in my two cents in the interest of balance:

I like the underscore varieties. I think it makes the code semantics more readable at a glance. Sure, syntax highlighting can do that as well, but I've always preferred the IDE/theme independent approach. Once you're used to it, it's nice to have the little guy immediately set off the "directly accessing an ivar here" alarm in your head.

Obviously, this is incredibly subjective.

As an addendum, the underscore prefix is really only especially dangerous with method names, where collisions won't be immediately exposed by the compiler, but it is probably still better to go with the suffix, if you're an underscore fan.


In general terms, why would anyone name their private variables with any suffix or prefix, most of the modern day tools do a great job in colorize them differently anyway. I prefer simply foo.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜