Objective C - Synthesize property [duplicate] - objective-c

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Prefixing property names with an underscore in Objective C
When synthesizing properties I found out that someone is doing:
#synthesize myVar = _myVar;
what is "_myVar" and which is the difference with simply doing :
#synthesize myVar;
Lastly when I should prefer the first solution to the last one?
Thanks
Luca

What _myVar really is in your example, is the name of the ivar that is backing your property. By default, when you synthesize a property, an ivar of the same name is created for you. So, you can use your property to set your ivar through setter/getter or the _myVar to directly access your variable (bypassing KVC/KVO of course).
EDIT:
From Apple's Coding Guidelines for Cocoa
...In many cases, when you use a declared property you also synthesize
a corresponding instance variable.
Make sure the name of the instance variable concisely describes the
attribute stored. Usually, you should not access instance variables
directly, instead you should use accessor methods (you do access
instance variables directly in init and dealloc methods). To help to
signal this, prefix instance variable names with an underscore (_)...

If you want to use some existing data member in setter and getter then it can be specify like that.
e.g. #synthesize personName=pName;
by this we can use pName instead of personName as per our convenience.

It the name of the private variable.
Se my answer on an other post: answer

Related

Objective C synthesized variable underscore prefix not working

I was reading the tutorials in the official Apple site about synthesizing properties at Apple. Here is an excerpt:
Unless you specify otherwise, the synthesized instance variable has the same name as the property, but with an underscore prefix. For a property called firstName, for example, the synthesized instance variable will be called _firstName.
However, later, it says:
Important: If you use #synthesize without specifying an instance variable name, like this:
#synthesize firstName;
the instance variable will bear the same name as the property.
In this example, the instance variable will also be called firstName, without an underscore.
These statements appear to be in disagreement. When I am using synthesize like synthesize numerator, and later trying to use _numerator, it is showing the following error: use of undeclared identifier _numerator.
Any idea what I am doing wrong?
You can declare instance variables and properties in the #interface.
In the implementation, you can use
#synthesize property = instancevariable;
When you do that, the compiler creates an instance variable named "instancevariable" if it doesn't exist yet, and generates code for the setter and getter as needed. The variable name is anything that you want to use.
#synthesize property;
on its own is the same as
#synthesize property = property;
which means an instance variable is created with the same name as the property, if it doesn't yet exist. Whether you created an instance variable yourself starting with an underscore doesn't matter. That instance variable will be just an instance variable, possibly causing major confusion in your code.
// No synthesize statement
is exactly the same as
#synthesize property = _property;
which means an instance variable is created with a leading underscore, if it doesn't yet exist. Whether you created an instance variable yourself without an underscore doesn't matter. That instance variable will be just an instance variable, possibly causing major confusion in your code. In this case, the compiler will give a warning.
There is one exception: If you implemented all the required methods (both setter and getter, or just the getter for a readonly proper) yourself, and you don't use #synthesize, then no instance variable will be created. If you use #synthesize, an instance variable will be created as described above.
So the best choice is to just declare the #property and nothing else; an instance variable starting with an underscore will be created. If you implement both setter and getter, or just the getter of a readonly property, you may not need an instance variable. If you need one, you can declare the instance variable or create it using #synthesize.
If I don't use synthesize, and don't declare setters and getters for variables as well, how will they be accessible?
Recent versions of Objective-C make #synthesize the default for properties, so you don't need to explicitly write #synthesize firstName; -- the compiler will take care of that for you.
As #TimReddy points out in a comment, the difference between the two passages that you quoted is that one is talking about behavior when you use the #synthesize directive explicitly (the ivar gets the same name as the property), while the other describes behavior when the compiler synthesizes the ivar automatically (the ivar name is the property name with an underscore prefix).

Naming of formal parameters in setters with synthesized properties [duplicate]

This question already has answers here:
Good practice for disambiguating argument names versus instance variable names in Objective-C
(3 answers)
Closed 9 years ago.
I have been learning and using Objective-C for quite some time now (it also kind of was my first OOP language) and I finally would like to know how to correctly name synthesized properties.
Let's take the following scenario:
I have got a property called someVariable.
#property (nonatomic, retain) NSString *someVariable;
and synthesize it
#synthesize someVariable;
How would the custom setter look like conventionally ?
1)
I would go ahead and say something like
-(void)setSomeVariable:(NSString *)someVar{
//input parameter MAY sound/look foreign due to the difference to the property
someVariable = someVar;
}
2) (illegal)
But I would like to name the formal parameter just like the property for the sake of readability and convenience. More like in Java like this:
-(void)setSomeVariable:(NSString *)someVariable{
//obviously illegal because this would call the setter over and over again
self.someVariable = someVariable;
}
3) (unconventional)
and according to what I have been reading in the past this
#synthesize someVariable = _someVariable;
is said to be unconventional and not supposed to be used.
So, am I correct in concluding that the way I have been doing it until now, is the only way to create a custom setter ?
3) is not unconventional, it's exactly what the compiler does if you don't provide the #synthesize statement.
This means that, without the #synthesize statement and the ivar declaration, you have an implicit ivar named _someVariable, and a custom setter would usually have a parameter named someVariable
-(void)setSomeVariable:(NSString *)someVariable {
_someVariable = someVariable;
}
Also note that providing custom setter and getter methods for a particular property indicates to the Xcode compiler to not provide the implicit ivar (here _someVariable). In the case of readonly properties, the same if true if you provide just the getter method.
WWDC 2012 session 405 provides a lot of details around Objective-C constructs for modern versions of the compiler.
EDIT
As H2CO3 has suggested in his answer, the code I wrote assumes you're using ARC. If you are using MRC, the setter method would rather be :
-(void)setSomeVariable:(NSString *)someVariable {
[someVariable retain];
[_someVariable release];
_someVariable = someVariable;
}

Why do #synthesize variable names begin with an _? [duplicate]

This question already has answers here:
What does #synthesize window=_window do?
(3 answers)
Closed 9 years ago.
I'm just starting to use Objective-C and I need to clarify something
When I #synthesize a #property, it is common convention to do the following:
#interface Class : ParentClass
#property propertyName
#end
#implementation
#synthesize propertyName = _propertyName;
#end
I've seen plenty of questions and answers suggesting that "_propertyName" is widely accepted as the "correct" way to synthesize properties. However, does it serve ANY purpose? Or is it merely to increase readability and identify instance variables?
It makes it so that if you accidentally leave off "self." you get a nice compiler error instead of silently not having your methods called.
From http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html
You Can Customize Synthesized Instance Variable Names
As mentioned earlier, the default behavior for a writeable property is
to use an instance variable called _propertyName.
If you wish to use a different name for the instance variable, you
need to direct the compiler to synthesize the variable using the
following syntax in your implementation:
#implementation YourClass #synthesize propertyName =
instanceVariableName; ... #end
Also:
Note: The compiler will automatically synthesize an instance variable
in all situations where it’s also synthesizing at least one accessor
method. If you implement both a getter and a setter for a readwrite
property, or a getter for a readonly property, the compiler will
assume that you are taking control over the property implementation
and won’t synthesize an instance variable automatically. If you still
need an instance variable, you’ll need to request that one be
synthesized: #synthesize property = _property;
By doing this the generated accessor actually got to know which variable(iVar) to use.
Yea, It increases the readability & also separates the private & public variables to understand & use. Private variable of Class generally written in "propertyName" format.You can say it is a coding convention where Private Variable Names use '' as prefix and Public Variables or Property Names are lowerCamelCase.

About naming the instance variable in Objective C

Sometimes we may explicitly specify the name of an instance variable in the synthesize statement, e.g.,
In SomeViewController.h,
//....
#property (nonatomic, retain) NSObject *variable;
//....
In SomeViewController.m,
//....
#synthesize variable = _variable;
//....
But why bother making this extra effort if the instance variable will be implicitly named as _variable even if we simply put it as:
#synthesize variable;
in the SomeViewController.m.
Can anyone share some idea on why it is necessary? Thank you :D
Just to avoid confusion (see comments): Using the = _variable part of the #synthesize is not required, nor is the #synthesize itself required any more.
This effort is only requied, when you want to link the property to a specific instance variable. With earlier Objective-C versions this part of the statement was required to set the name to something different from the property name, so when you want to call the iVar _variable and the property variable. The default would be variable (unlike your question). Without that = something ivar and property have the same name.
BTW, there is nothing wrong with using the same name for both. But having different names, a leading _ would do, makes it more clear to the programmer whether he/she accesses the ivar directly or though the accessor methods. Sometimes this is of vast importance, especially when not using ARC. Therefore it helps avoiding errors.
With current Objective-C, however, you could omit the #synthesize statement at all and go with the defaults in that case. The default automatically synthesized instance variable name would have a leading _ so _variable in your example.

what #synthesize variable = _variable will do?

I have seen code like that in the Application delegate in iPhone project for example.
what is the variable with the underscore means? can I use it as setter and getter for the variable?
also when releasing the variable should I use:
[variable release];
or
[_variable release];
Thanks.
In some coding conventions the underscore before instance variables is used to be able to quickly differentiate them from other variables. It also helps avoid naming conflicts with local variables in methods and subclass methods.
#synthesize variable = _variable
Creates a setter and getter that set/get the variable you set it to in this case _variable. So outside access uses code like object.variable which is really just returning _variable. however the class usually uses the _variable internally.
#synthesize variable = _variable;
The property name is "variable" and the instance variable that backs it up is named "_variable". You should use the accessors -variable and -setVariable: rather than accessing the ivar directly, except in -init and -dealloc, where you'd use _variable.
In your example variable is a property and _variable is an instance variable. For simplicity sake we can say that by synthesizing you are essentially instructing that the property ( in our case variable) will use the instance variable ( in our case _variable) for storing and retrieving values. What you are really doing is instructing the compiler to create implementations that match the specification given in the property declaration.
The suggested way of releasing when you are using a property will be to just assign it nil. This would essentially release the object and also set the instance variable to nil instead of being a dangling pointer.
If you were not using property then you can call the release on the instance variable and then ideally you want to set it to nil.