When setting the readonly attribute in the interface section this 'disables' the setter method for the property. I need some clarification with:
When to use _propertyName if our property is readwrite?
Also I understand we use setter methods for a degree of abstraction, rather than just assigning the value using _propertyName. Is there any other reason NOT to use _propertyName?
Here is some example code below. Thankyou.
Interface Section
@property (nonatomic, readonly) NSString *licensePlate;
@property (nonatomic, readonly) NSString *bodyColor;
Implmentation Section
-(id) initWithCarFeatures {
self = [super init]
if (self) {
_licensePlate = @"XSHJDS8687";
_bodyColor = @"blueColor";
}
return self;
}
The point is "encapsulation". No other files will be able to directly set the property. The property can be set only from the given file, for example, using init
, or using a specialized method.
Most people will tell you that you should use _property
directly only in init
method, dealloc
(if you are not using ARC) and of course, if you are implementing your own setter and getter. Even if the property is declared as readonly
, usually you declare it readwrite
in class extension. Therefore, it will stay readonly
for other files but it will be readwrite
for the implementation file (class) that declares it.
Many reasons, for example "inheritance" - setters can be overridden. For copy
properties, the copying is handled by the setter. With MRC (not ARC), setters are even more important (they handle retains and releases).