Xcode 4.5 Interface Builder Adds Underscores to Outlets

自作多情 提交于 2019-12-04 03:33:35

Yes, the behavior has changed slightly in Xcode 4.5.

... in the associated .m file, there is no @synthesize declaration.

In Xcode 4.5, the @synthesize statement is now optional, and properties are synthesized automatically. Automatically generated IBOutlet properties therefore no longer add @synthesize because it's no longer required.

... the code in dealloc prepends an _ on the property name

When properties are synthesized automatically (without an explicit @synthesize statement) the corresponding instance variable is prepended with an underscore. That's why it shows up as such in your dealloc method. This is so the instance variable and property names don't overlap.

This also means I cannot reference the property as normal

No. Accessing instance variables and properties has not changed. All that has changed is the default name of the instance variable. E.g.:

_foo = @"Bar"; // Setting an instance variable directly.
self.foo = @"Bar";  // Setting an instance variable via a property accessor method.

The underscore is merely a matter of style, so that it's more clear that you're accessing the instance variable rather than the property.

Note that you can add a @synthesize statement yourself, and that will force the name of the corresponding instance variable to be whatever you want it to be. Likewise, if you add your own property accessor methods then that will prevent the instance variable from being generated automatically.

Xcode now auto-synthesizes all properties to be an instance variable called _propertyName. In many cases you no longer need @synthesize or to declare an instance variable explicitly.

With XCode 4.5 the default is now to add the underscore to the underlying instance variable. But the only impact this has for you is that you need to refer to that variable with the underscore. Here is an example:

@property (retain) UIColor color;

In your implementation code you can refer to the color like this:

[_color set]; // Now do some drawing...

For the outside world things remain unchanged.

object.color = [UIColor redColor];

This change is based on a common practice to name instance variables with an underscore prefix to distinguish them from local variables in your code.

Also, note that you normally want to access your property as [self.propertyName doSomething];, which is why auto-prefixing the instance variable with an underscore to indicate privacy makes sense.

If you really have to, you access it as [_propertyName doSomething] if you let it auto synthesize, but that bypasses the getter. Or, you can @synthesize propertyName = propertyName; to be able to use [propertyName doSomething] again, but why would you?

I have found that if you use an underscore before your @property name you are again able to implement your desired methods like before.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!