开发者

Objective-C: why @synthesize foresees an assignment?

I noticed that the @synthesize directive admits an assignment to the property it receives, and I can't understand why.

I mean, I have in the application delegate's implementation file:

@synthesize window=_window;

W开发者_如何学编程hile if I have to synthesize a property into a view controller's .m file I can simply write:

@synthesize messageString;

without assigning it a _messageString.

I can't figure out why I should need the former syntax.


As mentioned, this is setting the ivar to be separate from the accessor. So, in the window=_window code above, your accessors would look like this.

- (UIWindow *)window
{
     return _window;
}

- (void)setWindow:(UIWindow *)w
{
     [w retain];
     [_window release];
     _window = w;
}

The usual reason for separating the ivar and the property is to prevent collision in a subclass. This way, subclasses can create a variable named window without colliding with the superclasses "window", since it is actually _window.


It just allows you to expose properties under a different name than the associated instance variables - which is useful because the conventions on property naming are quite well established, but the conventions on instance variables are much less well defined.


This is not an assignment. It just names the ivar the property is based on.


The former syntax (@synthesize window=_window) allows you to specify that the instance variable should have a separate name than the property. I believe that this doesn't make any real difference to the implementation, however it's a nice way for you to be able to ensure that your public accessors are separate from the private ivar.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜