window = _window
I've been doing a few tutorials on Core Data for the iPhone, and none of them seem to work. Luckily, one of the tutorial sites provided source code and one problem that kept popping up (and is hopefully the explanation as to why said tutorials weren't working), was this line:
@synthesize window = _window;
About half a dozen synthesizes like this would auto-generate i开发者_如何学Pythonn my tableview files, but none of the tutorials used them, which caused a ton of errors for me. The line in the working source code is:
@synthesize window;
So, why is this? I've read online that the first version of @synthesize
is for memory management purposes, but no one seems to be using it.
The only difference here is in how the instance variable is named when it's auto-generated.
With this version:
@synthesize window = _window;
You effectively get these (assuming you haven't set the @property
to readonly
):
UIWindow *_window;
- (UIWindow *)window;
- (void)setWindow:(UIWindow *)aWindow;
With the other version:
@synthesize window;
You get this:
UIWindow *window;
- (UIWindow *)window;
- (void)setWindow:(UIWindow *)aWindow;
The second version is equivalent to:
@synthesize window = window;
A statement like this:
@synthesize window = _window;
means window
is a property that maps to the instance/member variable _window
.
Wheras
@synthesize window;
is the same as
@synthesize window = window;
I've been having the same problems with the tutorials I've been working through.
For my stuff the way I could get it working with minimal change was to add the
UIWindow *window;
in the header file interface section as this was not being added in by Xcode automatically but was expected by the tutorial stuff.
I then changed the sections where it calls
[window addSubview:tabBarController.view];
to
[self.window addSubview:tabBarController.view];
That seems to work now. The tutorials I'm reading through were based a previous release of Xcode so I'm thinking things have changed. The UIWindow line is not added automatically and Xcode has started using _window
for its own stuff.
Would love it anyone could give a clearer explanation though, as I'm kind of stumbling in the dark here.
DO NOT use single leading underscores as a prefix for your ivar or method names. That's an Apple internal coding convention, and they do it so that their symbols won't collide with yours.
If you synthesize a property and tell it to use _window
in any subclass of a UIKit class that already has an ivar named _window
, you'll be clobbering code in the kit. Other very common ivar names that you might collide with are _delegate
, _target
, and _view
.
精彩评论