2

This is a follow-up question of: Why rename synthesized properties in iOS with leading underscores?

in MyDelegate.h

#import <UIKit/UIKit.h>

@interface MyAppDelegate

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) MyMainViewController *mainViewController;

@end

in MyDelegate.m

#import "MyAppDelegate.h"

@implementation MyAppDelegate

@synthesize window = _window;
@synthesize mainViewController = _mainViewController;

Besides what's explained in the original question about the benefit of the _ prefix, I am wondering why _window is accessible

@synthesize window = _window;

without defined anywhere, before it is used for the first time?

Community
  • 1
  • 1
ohho
  • 50,879
  • 75
  • 256
  • 383

2 Answers2

3

That is both the declaration and definition. The @synthesize directive is capable of creating both accessor methods and instance variables. From TOCPL, "Declared Properties: Property Implementation Directives":

You can use the form property=ivar to indicate that a particular instance variable should be used for the property...
For the modern runtimes (see “Runtime Versions and Platforms” in Objective-C Runtime Programming Guide), instance variables are synthesized as needed. If an instance variable of the same name already exists, it is used.

So if you already had a declaration of an ivar,

@interface MyAppDelegate : NSObject
{
    NSWindow * _window;
}

that would be used (and this was required in the "legacy" platform). Otherwise, it is created by the @synthesize directive. The result within the class is the same in either case, although it should be noted that synthesized variables are created as if they were declared with the @private directive; subclasses can access the property, but not the ivar directly. More investigation at the inimitable Cocoa With Love: Dynamic ivars: solving a fragile base class problem.

jscs
  • 63,694
  • 13
  • 151
  • 195
1
 @synthesize window = _window;

It's defined there. This is saying, you know that property I said was called window, well, in the background, make this an ivar called _window, so that if anyone types

window = blah blah

This gives a compiler error.

This prevents you accessing the ivar directly by accident instead of using the synthesized accessors.

jrturton
  • 118,105
  • 32
  • 252
  • 268