Why we are declaring same thing two time in .h file in iOS [duplicate] - header

I've seen in a few iPhone examples that attributes have used an underscore _ in front of the variable. Does anyone know what this means? Or how it works?
An interface file I'm using looks like:
#interface MissionCell : UITableViewCell {
Mission *_mission;
UILabel *_missionName;
}
#property (nonatomic, retain) UILabel *missionName;
- (Mission *)mission;
I'm not sure exactly what the above does but when I try to set the mission name like:
aMission.missionName = missionName;
I get the error:
request for member 'missionName' in something not a structure or union

If you use the underscore prefix for your ivars (which is nothing more than a common convention, but a useful one), then you need to do 1 extra thing so the auto-generated accessor (for the property) knows which ivar to use. Specifically, in your implementation file, your synthesize should look like this:
#synthesize missionName = _missionName;
More generically, this is:
#synthesize propertyName = _ivarName;

It's just a convention for readability, it doesn't do anything special to the compiler. You'll see people use it on private instance variables and method names. Apple actually recommends not using the underscore (if you're not being careful you could override something in your superclass), but you shouldn't feel bad about ignoring that advice. :)

The only useful purpose I have seen is to differentiate between local variables and member variables as stated above, but it is not a necessary convention. When paired with a #property, it increases verbosity of synthesize statements – #synthesize missionName = _missionName;, and is ugly everywhere.
Instead of using the underscore, just use descriptive variable names within methods that do not conflict. When they must conflict, the variable name within the method should suffer an underscore, not the member variable that may be used by multiple methods. The only common place this is useful is in a setter or in an init method. In addition, it will make the #synthesize statement more concise.
-(void)setMyString:(NSString*)_myString
{
myString = _myString;
}
Edit:
With the latest compiler feature of auto-synthesis, I now use underscore for the ivar (on the rare occasion that I need to use an ivar to match what auto-synthesis does.

It doesn't really mean anything, it's just a convention some people use to differentiate member variables from local variables.
As for the error, it sounds like aMission has the wrong type. What it its declaration?

This is only for the naming convention of synthesize properties.
When you synthesize variables in the .m file, Xcode will automatically provide you _variable intelligence.

Having an underscore not only makes it possible to resolve your ivars without resorting to using self.member syntax but it makes your code more readable since you know when a variable is an ivar (because of its underscore prefix) or a member argument (no underscore).
Example:
- (void) displayImage: (UIImage *) image {
if (image != nil) {
// Display the passed image...
[_imageView setImage: image];
} else {
// fall back on the default image...
[_imageView setImage: _image];
}
}

This seems to be the "master" item for questions about self.variableName vs. _variablename. What threw me for a loop was that in the .h, I had:
...
#interface myClass : parentClass {
className *variableName; // Note lack of _
}
#property (strong, nonatomic) className *variableName;
...
This leads to self.variableName and _variableName being two distinct variables in the .m. What I needed was:
...
#interface myClass : parentClass {
className *_variableName; // Note presence of _
}
#property (strong, nonatomic) className *variableName;
...
Then, in the class' .m, self.variableName and _variableName are equivalent.
What I'm still not clear on is why many examples still work, even tough this is not done.
Ray

instead of underscore you can use self.variable name or you can synthesise the variable to use the variable or outlet without underscore .

Missing from the other answers is that using _variable prevents you from absentmindedly typing variable and accessing the ivar rather than the (presumedly intended) property.
The compiler will force you to use either self.variable or _variable. Using underscores makes it impossible to type variable, which reduces programmer errors.
- (void)fooMethod {
// ERROR - "Use of undeclared identifier 'foo', did you mean '_foo'?"
foo = #1;
// So instead you must specifically choose to use the property or the ivar:
// Property
self.foo = #1;
// Ivar
_foo = #1;
}

Related

Property declaration in Objective-C [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How does an underscore in front of a variable in a cocoa objective-c class work?
So i have found out that you have to use underscore when synthesizing properties and that doesn't make a single bit of sense to me.
So, let's start.
In our .h file we write this line:
#property (nonatomic) double speed;
In our .m file we do this:
#synthesize speed = _speed;
Why? As far as I know, property makes an instance variable and creates setters and getters for it.
But what the hell does line
#synthesize speed = _speed
do?
As common sense tells me, we assign value in _speed to speed. Okay.
Where did we declare _speed? Why doesn't compiler give us an error? What is it supposed to mean? Why such an obfuscated code?
My questions here:
What happens if I do just
#synthesize speed;
without _speed, will I get error or some bugs?
What is the reason after this syntax? What were they thinking when making it? Where does _speed come from? What is it? Is it a pointer or a real value? What is going on?
Well, _speed is the instance variable used by the property. If you really want to declare it fully, you need to write:
#interface Foo
{
double _speed;
}
#property double speed;
#end
#implementation Foo
#synthetize speed = _speed;
#end
Now Xcode 4.4 is unleashed, most of that stuff is unnecessary and should be omitted for sanity.
Basically, all you have to do is:
#interface Foo
#property double speed;
#end
No instance variable, no #synthetize, and everything still works as before. You can either use self.speed or self->_speed for direct access.
You do not HAVE to do that. It is just common practice. The ...=_speed will create an property named _speed and its setter and getter will be named after speed. That allows you to distinguish between
self.speed = value;
and
speed = value;
because the latter will create a compiler error.
_speed = value;
would be correct in that case.
That helps avoiding retain/release related errors because the setter will retain the object and the simple assignmen will not.
(self.speed = ... will call the setter!)
If you omit the "=_speed" on the synthesize statement then the property will be named "speed" only. If you don't make any mistakes, then this will work perfectly fine.
okay you don't have to do this...
However by doing so means that in your implementation you cannot use the non underscore name of that property, because in fact by doing so you would be getting mixed up with accessing the iVar directly rather then through the property.
So in other words by doing this:
#synthesize myProperty;
In your code you can reference it by myProperty (iVar) or self.myProperty (property - with the access rules - readonly/readwrite, getter, setter etc...) this can of course be confusing if you are using some kind of rules like:
#property(nonatomic, retain, getter = anotherProperty) NSNumber myProperty
By accessing this with myProperty in code, you would expect to get value of anotherProperty
This would only be possible by doing:
self.myProperty
So in Objective-C we can do the following to avoid this:
#synthesize myProperty = _myProperty;
Therefore in code it is actually an error to reference myProperty directly, instead you must do self.myProperty (property access) or _myProperty (iVar access).
Its a naming convention, you don't have to do it. People tend to do this so that they can distinguish between the instance variable and the property.
Usually it goes
.h
#interface myClass : NSObject
{
NSNumber *_speed
}
#property (nonatomic, strong) NSNumber *speed;
.m
#implementation
#syntesize speed = _speed;
Nothing bad will happen -- it's fine to just write #synthesize speed. Using _speed just makes the underlying instance variable _speed instead of speed. Most people do this to keep from accidentally accessing the ivar directly, instead of through thr getter.
From the documentation
#synthesize speed = _speed; will point the property speed to the instance variable _speed.
You do not have to do this. #synthesize speed works just fine.
In environment with manual memory management:
Why do I need an instance variable name at all?
You need to release memory which may be used by your properties in the dealloc
You may use self.field = nil but this approach may cause problems
So you need an instance variable which is used behind this property so you can [_field release]; it in dealloc.
The same if you need to access your property in the initializer.
Why do I need an underscore in the instance variable name?
To never accidentally use ivar directly and break memory management contract for the property
#property (retain) UILabel *label;
...
#synthesize label;
...
-(void)viewDidLoad {
[super viewDidLoad];
label = [[[UILabel alloc] initWithFrame:frame] autorelease];
}
here by accidentally missing self. you made label potential 'dangling pointer'. If you used #synthesize label = _label; above code would produce a compiler error.
Local variables or method parameter names often tend to be the same as the property name - if you use underscored instance variable it won't cause any problems

Differentiate between iVar and Method Parameter?

I have a property like this:
#property (nonatomic, strong) IBOutlet UIImageView *backgroundImageHolder;
I want to adjust the setter, and XCode fills out the method signature like this:
-(void)setBackgroundImageHolder:(UIImageView *)backgroundImageHolder {
However, to actually do anything in the method, I must change the parameter backgroundImageHolder to something like backgroundImageHolderIn. Is there any way to avoid this? Is there any way to set the iVar without reinvoking the setter (causing an endless loop), or just referring to the parameter again?
I just tried:
self->backgroundImageHolder = backgroundImageHolder;
but the compiler warns me anyway.
Note: I am using the automagically generated iVar that the compiler makes for the property, but by default its name is the same.
You can give tell the compiler how to name the generated ivar:
#synthesize propertyName = iVarName;
If there actually exists an ivar named iVarName that one is used. If it doesn't exist the compiler creates it for you.
Like:
#synthesize backgroundImageHolder = myBackgroundImageHolder;
Now you can access the instance variable myBackgroundImageHolder. You don't need to declare it in the interface first.
Well, the conflicting parameter name seems to be pretty well covered by now. Basically, you have to either:
Rename the incoming argument
Rename the synthesized iVar
Once you have a method argument that differs from the iVar you're attempting to set, you have everything you need to write a custom setter. To avoid the infinite loop, you have to not call the setter you're currently implementing, whether it be via dot syntax or method brace syntax. Instead, refer directly to the backing iVar. You'll need to take care to manually implement the memory management semantics you declared in the property though (assign vs. retain, etc.):
// Backed by _myProperty iVar.
- (void)setMyProperty:(NSInteger)myProperty {
// Insert custom code here...
[self setMyProperty:myProperty]; // Obviously bad.
self.myProperty = myProperty; // Less obviously bad (thanks dot syntax)
// but semantically identical to the previous line.
_myProperty = myProperty // Good, (assuming assign semantics).
}
Compiler warns you because when you declare #property it creates instance variable with exact same name as a property (and as a parameter of a setter method). One way to avoid it is to create differently named instance variable and then pair it with property using #synthesize like this:
// .h
#interface Foo : NSObject {
IBOutlet UIImageView *myfooImageView;
}
#property (nonatomic, retain) UIImageView *publicFooImageView;
// .m
#implementation Foo
#synthesize publicFooImageView=myfooImageView;
#end
The clearest thing to do would be this:
In your header, define an iVar for backgroundImageHolder like so
#interface Something : NSObject
{
IBOutlet UIImageView *_backgroundImageHolder
}
Notice the leading underscore.
Then in your .m file, use either the synthesize call like so:
#synthesize backgroundImageHolder=_backgroundImageHolder;
or just define the getter and setter methods yourself: Then you are able to access the ivar via "_backgroundImageHolder" without any danger of accidentally calling the setter again.

Why put underscore "_" before variable names in Objective C [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How does an underscore in front of a variable in a cocoa objective-c class work?
In objective C I am seeing lots of code with a underscore before variable names e.g _someVariable
why is that? also how to you write accessors i.e get and set method for such a variable.
The underscores are often used to show that the variables are instance variables. It is not really necessary, as ivars can have the same name as their properties and their accessors.
Example:
#interface MyClass : NSObject {
NSString *_myIVar; // can be omitted, see rest of text
}
// accessors, first one is getter, second one is setter
- (NSString *) myIVar; // can be omitted, see rest of text
- (void) setMyIVar: (NSString *) value; // can be omitted, see rest of text
// other methods
#property (nonatomic, copy) NSString *myIVar;
#end
Now, instead of declaring and coding the accessors myIVar and setMyIVar: yourself, you can let the compiler do that. In newer versions, you don't even have to declare myIVar in the interface. You just declare the property and let the compiler synthesize the rest for you. In the .m file, you do:
#implementation MyClass
#synthesize myIVar; // generates methods myIVar and setMyIVar: for you,
// with proper code.
// also generates the instance variable myIVar
// etc...
#end
Be sure to finalize the string:
- (void) dealloc {
[myIVar release];
[super dealloc];
}
FWIW, if you want to do more than the default implementation of the getter or setter do, you can still code one or both of them yourself, but then you'll have to take care of memory management too. In that case, the compiler will not generate that particular accessor anymore (but if only one is done manually, the other will still be generated).
You access the properties as
myString = self.myIVar;
or, from another class:
theString = otherClass.myIVar;
and
otherClass.myIVar = #"Hello, world!";
In MyClass, if you omit self., you get the bare ivar. This should generally only be used in the initializers and in dealloc.
Don't do it.
Single leading underscores are an Apple internal coding convention. They do it so that their ivar names won't collide with yours. If you want to use a prefix on your ivar names, use anything but a single underscore.
this is a naming convention normally used for c++ to define instance variable which are private
like in a class u may have
private:
int __x;
public:
int GetX()
{
return this.__x;
}
this is a naming convention, i was forced to use in c++. However my teacher never told us the name of the naming convention. But i feel this is helpfull and readable specially when u are not using java naming conventions.

Question about #synthesize

When you create a new application from Xcode that embed CoreData you got those lines in the implementation file of the delegate:
#synthesize window=_window;
#synthesize managedObjectContext=__managedObjectContext;
What are the differences between using only a underscore or double it? What's the difference on writing only:
#synthesize window;
A leading underscore is a naming convention helpful to differentiate between instance variables and accessors. For the compiler it is just a common ivar rename.
Consider the difference (non ARC code):
self.date = [NSDate date]; // OK, the setter releases the old value first
date = [NSDate date]; // WRONG, skipping the setter causes a memory leak
_date = [NSDate date]; // WRONG but easier to see it's not a local variable
With ARC variables won't be leaked, but it is still wrong to skip the #property attributes:
#property (copy) string;
// ...
self.string = someString; // OK, string is copied
string = someString; // WRONG string is retained but not copied
_string = someString; // WRONG but hopefully easier to see
Even worst, some APIs like Core Data rely on KVC notifications to perform lazy loading. If you accidentally skip the accessors, your data will come back as nil.
This is the reason you often find #synthesize var=_var, which makes
self.var an accessor reference (invoking setters and getters),
_var a direct access reference (skipping setters and getters),
and var an invalid reference.
Given that #synthesize var=_var is autogenerated by LLVM 4.0 when #synthesize is omitted, you can consider this the default naming convention in Objective-C.
Keep reading for details...
Modern runtime
In Objective-C 2.0 you declare variables like this:
#interface User : NSObject
#property (nonatomic, assign) NSInteger age;
#end
#implementation User {
#synthesize age; // this line can be omitted since LLVM 4.0
#end
which is translated by the compiler as follows:
#interface User : NSObject {
NSInteger age;
}
#end
#implementation User
-(void)setAge:(NSInteger)newAge {
age=newAge;
}
-(void)age {
return age;
}
#end
If you prefer to use the underscore convention just add the following:
#synthesize age=_age;
That's all you need because with the modern runtime, if you do not provide an instance variable, the compiler adds one for you. Here is the code that gets compiled:
#interface User : NSObject {
NSInteger _age;
}
#end
#implementation User
-(void)setAge:(NSInteger)newAge {
_age=newAge;
}
-(void)age {
return _age;
}
#end
What happens if you add both the ivar and the #property? If the variable has the same name and type, the compiler uses it instead generating a new variable. Quoting The Objective-C Programming Language > Declared Properties > Property Implementation Directives:
There are differences in the behavior of accessor synthesis that
depend on the runtime:
For the modern runtimes, instance variables are synthesized as needed. If an instance variable of the same name already exists, it is
used.
For the legacy runtimes, instance variables must already be declared in the #interface block of the current class. If an instance
variable of the same name as the property exists, and if its type is
compatible with the property’s type, it is used —otherwise, you get a
compiler error.
Legacy runtime
But if you need to support the legacy runtime you must either provide an instance variable with the same name and compatible type of the property or specify another existing instance variable in the #synthesize statement.
So the legacy code without underscores would be:
#interface User : NSObject {
NSInteger age;
}
#property (nonatomic, assign) NSInteger age;
#end
#implementation User
#synthesize age;
#end
Or if you prefer the underscore convention:
#interface User : NSObject {
NSInteger _age;
}
#property (nonatomic, assign) NSInteger age;
#end
#implementation User
#synthesize age = _age;
#end
What is the best way?
Apple discourages the use of underscore in methods, but not on variables!.
Apple on methods: Coding Guidelines for Cocoa: Typographic Conventions:
Avoid the use of the underscore
character as a prefix meaning private,
especially in methods. Apple reserves
the use of this convention. Use by
third parties could result in
name-space collisions; they might
unwittingly override an existing
private method with one of their own,
with disastrous consequences.
Apple on variables: Declared Properties and Instance Variables
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 (_),
for example: #implementation MyClass { BOOL _showsTitle; }
ISO/IEC 9899 7.1.3 Reserved identifiers (aka C99):
All identifiers that begin with an underscore and either an uppercase
letter or another underscore are
always reserved for any use.
All
identifiers that begin with an
underscore are always reserved for use
as identifiers with file scope in both
the ordinary and tag name spaces.
On top of that, double leading underscore is traditionally reserved for the vendor of the preprocessor / compiler / library. This avoids the case where you use __block somewhere in your code, and Apple introduces that as a new non-standard keyword.
Google Objective-C Style guide:
Variable Names Variables names start
with a lowercase and use mixed case to
delimit words. Class member variables
have trailing underscores. For
example: myLocalVariable,
myInstanceVariable_. Members used for
KVO/KVC bindings may begin with a
leading underscore iff use of
Objective-C 2.0's #property isn't
allowed.
Google's trailing underscore doesn't force you to type one more character before Xcode fires the autocomplete, but you'll realize it is an instance variable slower if the underscore is a suffix.
Leading underscore is also discouraged in C++ (see What are the rules about using an underscore in a C++ identifier?) and Core Data properties (try adding a leading underscore in the model and you'll get "Name must begin with a letter").
Whatever you chose, collisions are unlikely to happen, and if they do, you'll get a warning from the compiler. When in doubt, use the default LLVM way: #synthesize var=_var;
I own an edit of this post to reading A Motivation for ivar decorations by Mark Dalrymple. You may want to check it out.
You can use just
#synthesize window;
if your instance variable is named 'window', however, some people use a naming convention of prefixing all instance variables with underscore, but still prefer to have their getters and setters without the underscore prefix, thats what the 'window=_window' means.
I don't know what double underscore means, but I suspect it's also a matter of a naming convention.

What is the difference between ivars and properties in Objective-C

What is the semantic difference between these 3 ways of using ivars and properties in Objective-C?
1.
#class MyOtherObject;
#interface MyObject {
}
#property (nonatomic, retain) MyOtherObject *otherObj;
2.
#import "MyOtherObject.h"
#interface MyObject {
MyOtherObject *otherObj;
}
#property (nonatomic, retain) MyOtherObject *otherObj;
3.
#import "MyOtherObject.h"
#interface MyObject {
MyOtherObject *otherObj;
}
Number 1 differs from the other two by forward declaring the MyOtherObject class to minimize the amount of code seen by the compiler and linker and also potentially avoid circular references. If you do it this way remember to put the #import into the .m file.
By declaring an #property, (and matching #synthesize in the .m) file, you auto-generate accessor methods with the memory semantics handled how you specify. The rule of thumb for most objects is Retain, but NSStrings, for instance should use Copy. Whereas Singletons and Delegates should usually use Assign. Hand-writing accessors is tedious and error-prone so this saves a lot of typing and dumb bugs.
Also, declaring a synthesized property lets you call an accessor method using dot notation like this:
self.otherObj = someOtherNewObject; // set it
MyOtherObject *thingee = self.otherObj; // get it
Instead of the normal, message-passing way:
[self setOtherObject:someOtherNewObject]; // set it
MyOtherObject *thingee = [self otherObj]; // get it
Behind the scenes you're really calling a method that looks like this:
- (void) setOtherObj:(MyOtherObject *)anOtherObject {
if (otherObject == anOtherObject) {
return;
}
MyOtherObject *oldOtherObject = otherObject; // keep a reference to the old value for a second
otherObject = [anOtherObject retain]; // put the new value in
[oldOtherObject release]; // let go of the old object
} // set it
…or this
- (MyOtherObject *) otherObject {
return otherObject;
} // get it
Total pain in the butt, right. Now do that for every ivar in the class. If you don't do it exactly right, you get a memory leak. Best to just let the compiler do the work.
I see that Number 1 doesn't have an ivar. Assuming that's not a typo, it's fine because the #property / #synthesize directives will declare an ivar for you as well, behind the scenes. I believe this is new for Mac OS X - Snow Leopard and iOS4.
Number 3 does not have those accessors generated so you have to write them yourself. If you want your accessor methods to have side effects, you do your standard memory management dance, as shown above, then do whatever side work you need to, inside the accessor method. If you synthesize a property as well as write your own, then your version has priority.
Did I cover everything?
Back in the old days you had ivars, and if you wanted to let some other class set or read them then you had to define a getter (i.e., -(NSString *)foo) and a setter (i.e., -(void)setFoo:(NSString *)aFoo;).
What properties give you is the setter and getter for free (almost!) along with an ivar. So when you define a property now, you can set the atomicity (do you want to allow multiple setting actions from multiple threads, for instance), as well as assign/retain/copy semantics (that is, should the setter copy the new value or just save the current value - important if another class is trying to set your string property with a mutable string which might get changed later).
This is what #synthesize does. Many people leave the ivar name the same, but you can change it when you write your synthesize statement (i.e., #synthesize foo=_foo; means make an ivar named _foo for the property foo, so if you want to read or write this property and you do not use self.foo, you will have to use _foo = ... - it just helps you catch direct references to the ivar if you wanted to only go through the setter and getter).
As of Xcode 4.6, you do not need to use the #synthesize statement - the compiler will do it automatically and by default will prepend the ivar's name with _.