Domanda

When setting the readonly attribute in the interface section this 'disables' the setter method for the property. I need some clarification with:

  1. What is the point of the readonly property if we can just set it using _propertyName?
  2. When to use _propertyName if our property is readwrite?

  3. 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;
}
È stato utile?

Soluzione

  1. 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.

  2. 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.

  3. 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).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top