Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 580
Howard Avatar asked Apr 15 '11 16:04

Howard


3 Answers

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

like image 83
Todd Hopkinson Avatar answered Oct 14 '22 14:10

Todd Hopkinson


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.

like image 40
Jano Avatar answered Oct 14 '22 14:10

Jano


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
like image 37
Kendall Helmstetter Gelner Avatar answered Oct 14 '22 15:10

Kendall Helmstetter Gelner