繁体   English   中英

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

[英]Further clarification of _property after readonly attribute?

在接口部分设置readonly属性时,“禁用”属性的setter方法。 我需要澄清一下:

  1. 如果我们可以使用_propertyName设置它,那么readonly属性的意义是什么?
  2. 如果我们的属性是readwrite,何时使用_propertyName?

  3. 另外我理解我们使用setter方法进行一定程度的抽象,而不是仅使用_propertyName分配值。 还有其他原因不使用_propertyName吗?

以下是一些示例代码。 谢谢。

接口部分

@property (nonatomic, readonly) NSString *licensePlate;
@property (nonatomic, readonly) NSString *bodyColor;

实施部分

-(id) initWithCarFeatures {
    self = [super init]
    if (self) {
        _licensePlate = @"XSHJDS8687";
        _bodyColor = @"blueColor";
    }
    return self;
}
  1. 关键是“封装”。 没有其他文件可以直接设置属性。 该属性只能从给定文件中设置,例如,使用init或使用专门方法。

  2. 大多数人会告诉你,你应该只在init方法, dealloc (如果你没有使用ARC)中直接使用_property ,当然,如果你正在实现自己的setter和getter。 即使该属性被声明为readonly ,通常readwrite在类扩展中声明它为readwrite 因此,对于其他文件,它将保持readonly ,但是对于声明它的实现文件(类)将进行readwrite

  3. 许多原因,例如“继承” - 设置者可以被覆盖。 对于copy属性,复制由setter处理。 使用MRC(不是ARC),setter甚至更重要(它们处理保留和释放)。

暂无
暂无

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

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