简体   繁体   English

在readonly属性之后进一步澄清_property?

[英]Further clarification of _property after readonly attribute?

When setting the readonly attribute in the interface section this 'disables' the setter method for the property. 在接口部分设置readonly属性时,“禁用”属性的setter方法。 I need some clarification with: 我需要澄清一下:

  1. What is the point of the readonly property if we can just set it using _propertyName? 如果我们可以使用_propertyName设置它,那么readonly属性的意义是什么?
  2. When to use _propertyName if our property is readwrite? 如果我们的属性是readwrite,何时使用_propertyName?

  3. Also I understand we use setter methods for a degree of abstraction, rather than just assigning the value using _propertyName. 另外我理解我们使用setter方法进行一定程度的抽象,而不是仅使用_propertyName分配值。 Is there any other reason NOT to use _propertyName? 还有其他原因不使用_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;
}
  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. 该属性只能从给定文件中设置,例如,使用init或使用专门方法。

  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. 大多数人会告诉你,你应该只在init方法, dealloc (如果你没有使用ARC)中直接使用_property ,当然,如果你正在实现自己的setter和getter。 Even if the property is declared as readonly , usually you declare it readwrite in class extension. 即使该属性被声明为readonly ,通常readwrite在类扩展中声明它为readwrite Therefore, it will stay readonly for other files but it will be readwrite for the implementation file (class) that declares it. 因此,对于其他文件,它将保持readonly ,但是对于声明它的实现文件(类)将进行readwrite

  3. Many reasons, for example "inheritance" - setters can be overridden. 许多原因,例如“继承” - 设置者可以被覆盖。 For copy properties, the copying is handled by the setter. 对于copy属性,复制由setter处理。 With MRC (not ARC), setters are even more important (they handle retains and releases). 使用MRC(不是ARC),setter甚至更重要(它们处理保留和释放)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM