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 ininit
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 asreadonly
, usually you declare itreadwrite
in class extension. Therefore, it will stayreadonly
for other files but it will bereadwrite
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).
Further clarification of _property after readonly attribute?
-
25-09-2022 - |
質問
When setting the readonly attribute in the interface section this 'disables' the setter method for the property. I need some clarification with:
- What is the point of the readonly property if we can just set it using _propertyName?
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;
}
解決
所属していません StackOverflow