2

When reading apple generated template code as well as in documentation, I see _ (underscore) and __ (double underscore). Example would be the code generated on checking off core data option:

@synthesize window = _window;
@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;

What does each of this mean? I understand _ refers to a backing private variable. What does __ mean?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Vinod
  • 93
  • 5
  • Guess it has been explained very well in this thread http://stackoverflow.com/questions/5466496/why-rename-synthesized-properties-in-ios-with-leading-underscores – Bruce Li Dec 07 '11 at 15:21
  • It's just a naming convention ... don't know what's __ is trying to say though, maybe it's an even more private variable. – Felix Dec 07 '11 at 15:22
  • Bruce Li, I saw that link, it does not mention anything about double underscore – Vinod Dec 07 '11 at 15:39

2 Answers2

1

Its often confusing at first glance as to when you are using the getter/setter methods and when you are accessing the ivar directly.

The alternative is name the ivar differently from the property. A common approach is to use an underscore to prefix the ivars names, like so -

@interface RootViewController : UITableViewController 
{
    NSDate *_timestamp;
}
@property (nonatomic, retain) NSDate *timestamp;

To connect the property (whose name has not changed) the sythensize statement gets an extra option:

@implementation RootViewController

@synthesize timestamp = _timestamp;

Essentially, if an ObjectiveC programmer declares ivars following this convention (and they should) and uses the basic syntax @synthesize _window; then the usage for the property becomes somewhat ugly: classInstance._window = myWindow or [classInstance set_window:myWindow]. Using the syntax @synthesize window=_window; allows the Obj-C programmer to utilize a popular programming standard (preceding ivars with _) while simultaneously having property accessors that use the Apple standard classInstance.window = myWindow and [classInstance setWindow:myWindow].

Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264
0

Apple's documentation suggest NOT to use single underscores in your project (as it reserved by apple itself: best-known example is _cmd ). But underscore is traditional c-style modifier for privateness of identifier, so double underscore is a solution to make private identifier for your variable.

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html

Names of most private methods in the Cocoa frameworks have an underscore prefix (for example, _fooData ) to mark them as private. From this fact follow two recommendations.

Don’t use the underscore character as a prefix for your private methods. Apple reserves this convention.
Oleg Trakhman
  • 2,082
  • 1
  • 17
  • 35