[英]Further clarification of _property after readonly attribute?
在接口部分设置readonly属性时,“禁用”属性的setter方法。 我需要澄清一下:
如果我们的属性是readwrite,何时使用_propertyName?
另外我理解我们使用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;
}
关键是“封装”。 没有其他文件可以直接设置属性。 该属性只能从给定文件中设置,例如,使用init
或使用专门方法。
大多数人会告诉你,你应该只在init
方法, dealloc
(如果你没有使用ARC)中直接使用_property
,当然,如果你正在实现自己的setter和getter。 即使该属性被声明为readonly
,通常readwrite
在类扩展中声明它为readwrite
。 因此,对于其他文件,它将保持readonly
,但是对于声明它的实现文件(类)将进行readwrite
。
许多原因,例如“继承” - 设置者可以被覆盖。 对于copy
属性,复制由setter处理。 使用MRC(不是ARC),setter甚至更重要(它们处理保留和释放)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.