What is the defference if I called
NSString *theNameToDisplay = _name;
or
NSString *theNameToDisplay = self.name;
<
really no difference, in assigning to other object but it will make great deal of difference if the assignment is done other way around means like self.name = theNameToDisplay;
this will be different as the value in theNameToDisplay
will get affected by the @property
attributes.
The first one is to access a variable directly. The second one is accessing it through the property.
Before asking such question you had better read any objective c properties tutorial...try this http://www.raywenderlich.com/2712/using-properties-in-objective-c-tutorial or any other. If you created a property you must(ok, should) access an ivar through it so that setter method is called:
- (void)setMyProp:(NSArray *)myProp {
[myProp retain];
[_myProp release];
_myProp = myProp;
}
Assume you have in your .m file this line (and don't have any overriden methods to direct access to _name)
@synthesize name = _name;
It mean that property name
(self.name) will use variable _name when you try to access it. In this case self.name
is equal to _name
But if you have dynamic property for name, something like this :
-(NSString)name{
return @"1234";
}
then there is a difference. self.name
will always return 1234, but _name can be not equal to this value.
Example:
_name = @"555";
NSLog(_name);
NSLog(self.name);
Result:
2012-02-09 14:27:49.931 ExampleApp[803:207] 555
2012-02-09 14:27:49.933 ExampleApp[803:207] 1234
See the other answers about the setter part of properties, this is about getters:
Normally, there is no difference in using the getter (self.name
) or the ivar directly (_name
, name
, name_
depending on your taste).
However, there might be cases where something (semi-)intelligent is happening under the hood, and the getter hides some magic. Imagine this custom getter:
-(NSString*)name
{
if ( _name == nil ) return @"No name set";
return _name;
}
Or imagine that you rework your class and the _name
ivar gets dropped in favor of a person
property encompassing more information, and you want your code to still work without much hassle:
-(NSString*)name
{
return self.person.name;
}
People may or may not like such an approach, but that is outside the scope of this question. The point is, it may happen. So the better choice is to always use the getter.
Consider the following code:
NSString *theNameToDisplay = _name;
self.name = @"foo";
NSLog(@"%@", theNameToDisplay);
This may result in a crash because when you set the property, the old value will be released, so theNameToDisplay
becomes a dangling pointer. Note that with NSString
this does not necessarily happen, especially with literal strings, but it could. It also won't happen when you have ARC enabled.
self.name
on the other hand is roughly equivalent to: [[_name retain] autorelease]
so theNameToDisplay
would still remain valid until the method returns.