Question

being relative new to programming iOS apps, I find it very useful to start off with some sample code. Hence, I ended up with a .m file, that starts with some lines that look like

@synthesize valueOne= _valueOne;

I noticed that having such a syntax makes it impossible to programmatically set properties of valueOne, for instance doing things like

valueOne.tag = 3

Therefore, for my own purposes, I have outcommented the "=_valueOne" part, without any noticeable harm to the functionality of the code.

What is the significance of such syntax, and what has been the consideration of the author of my sample code to use it?

Thanks in advance

Was it helpful?

Solution

This syntax is synthesizing the backing ivar for valueOne under the name _valueOne. You can simply write your code to look like

_valueOne.tag = 3;

That said, it's generally considered better to use the property accessors whenever possible, so you'd typically write this as

self.valueOne.tag = 3;

The notable exceptions to this are when you're in -init, -dealloc, or your own custom getter/setter you still want to use the ivar directly.


Using a prefixed underscore on ivar names is generally considered good practice, because it means if you write valueOne.tag = 3; and you meant to use the property, you get a compiler error instead of silently using the ivar. If you intend to use the ivar, you can just use the underscore prefix, as _valueOne.tag = 3;.

This is such a common practice that the auto-synthesis behavior of modern clang will use the leading-underscore style for ivars. This means that if you delete the @synthesize line entirely, it will behave as though you had @synthesize valueOne = _valueOne;.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top