ohho
ohho

Reputation: 51941

Why _window is accessible without defining UIWindow *_window?

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?

Upvotes: 2

Views: 266

Answers (2)

jscs
jscs

Reputation: 64002

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.

Upvotes: 3

jrturton
jrturton

Reputation: 119242

 @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.

Upvotes: 1

Related Questions