In the following common sample,
////
@interface MyObject : NSObject
{
@public
NSString * myString_;
}
@property (assign) NSString * myString;
@end
@implementation MyObject
@synthesize myString = myString_;
@end
////
why declare myString_
in the interface at all?
I ask because we can still get and set myString
in the implementation using self.myString
, [self myString]
, self.myString = ...
and [self setMyString:...]
and in fact we must if instead it's being retained.
This is a matter of preference/convention for some. By default, doing:
@property (assign) NSString * myString;
...followed by:
@synthesize myString;
...will give you three things. You get a setter method that can be accessed as self.myString = @"newValue"
or [self setMyString:@"newValue"]
, a getter method that can be accessed as NSString* temp = self.myString
or NSString* temp = [self myString]
, and an instance variable named myString
that be be accessed directly inside of your class (i.e. without going through the getter and setter) and used to set and get the property value, and which is used internally to back the property.
If you like you can do @synthesize myString = someOtherVarName
, and then you still get the setters and getters just as before, but instead of the myString
instance variable the someOtherVarName
instance variable is used to back the property, and no myString
variable is created.
So why ever use the more verbose syntax? There is never any case that requires that you do so, but some people prefer to do so when dealing with properties that are declared retain
or copy
. The reason for this being that setting a property declared retain
or copy
via its generated setter method will affect the retain-count of the object being set/unset. Doing the same thing by accessing the instance variable directly will not.
So by aliasing the instance variable to something else, you can make a distinction in the code along the lines of "anything that does xxx.myString = Y
is modifying the retain count, while anything that does someOtherVarName = Y
is not". Again, it's not necessary to do this, but some people prefer to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With