Xcode4 templates now use underscore on iVars?
Asked Answered
S

1

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.
Smilacaceous answered 26/5, 2011 at 13:49 Comment(4)
Take a look to this question.Dihydrostreptomycin
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.Panathenaea
Thank you @ NSResponder, thats what I was looking for, much appreciated ...Smilacaceous
I don't think NSResponder is right. Because Apple's own documentation now recommends it in your own variables. See developer.apple.com/library/ios/#documentation/iphone/…. 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.Ossie
C
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.

Cultivated answered 26/5, 2011 at 13:55 Comment(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.Benny

© 2022 - 2024 — McMap. All rights reserved.