3

I have noticed that with Xcode4 Apple has updated the application templates to include underscores before instance variables.

// Xcode4
@property (nonatomic, retain) IBOutlet UIWindow *window;
@synthesize window = _window;

.

// Xcode3
@property (nonatomic, retain) IBOutlet UIWindow *window;
@synthesize window;

I know there are differing opinions on the usefulness of this but I was just curious if the updated templates where:

  • (1) Highlighting a new best practice.
  • (2) Showing how Apple does things but meaning for you to do it the old way.
  • (3) Its just personal taste, it does not matter.
Community
  • 1
  • 1
fuzzygoat
  • 26,573
  • 48
  • 165
  • 294
  • Take a look to [this](http://stackoverflow.com/questions/822487/how-does-an-underscore-in-front-of-a-variable-in-a-cocoa-objective-c-class-work) question. – Alex Terente May 26 '11 at 13:59
  • 1
    In this case it's correct, because it's referring to an ivar declared in an Apple framework. You still shouldn't use single leading underscores for your own ivar names. – NSResponder May 30 '11 at 08:41
  • Thank you @ NSResponder, thats what I was looking for, much appreciated ... – fuzzygoat May 30 '11 at 18:56
  • I don't think NSResponder is right. Because Apple's own documentation now recommends it in your own variables. See http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iPhone101/Articles/03_AddingViewController.html. Rather, it looks like a reversal of policy by Apple, and a good one I think because there's less confusion between ivars and the properties that access them. – Rhubarb Aug 29 '11 at 19:10

1 Answers1

6

It's interesting because in the past (pre-iOS), Apple used to discourage the use of underscore prefixes for ivars:

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. See “Private Methods” for suggestions on conventions to follow for private API.

But with a modern Objective-C runtime, I believe ivar naming conflicts in subclasses has been eliminated, so this is not a problem anymore. So I think that's why they're making the templates use an underscore prefix by default, to match what Apple's internal code looks like.

Daniel Dickison
  • 21,832
  • 13
  • 69
  • 89
  • 1
    Ivar naming conflicts haven’t been eliminated — if a superclass declares an ivar in its `@interface` block, no subclass may declare an ivar with the same name. That said, the modern runtime features the non-fragile ABI, which allows _class extensions_ to define their own ivars, which in certain cases allows the removal of ivars from the `@interface` block entirely which, in turn, helps with preventing name conflicts. –  May 26 '11 at 14:09